package com.credithc.customers.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.credithc.baseserv.core.message.MessageFactory;
import com.credithc.baseserv.core.utils.UUIDUtils;
import com.credithc.customers.api.service.ICustomerUnifyService;
import com.credithc.customers.api.service.RedisService;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.configure.PropertiesConfig;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.constants.TableEnum;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.mapper.*;
import com.credithc.customers.base.po.*;
import com.credithc.customers.base.ro.*;
import com.credithc.customers.base.service.IBaseCustomerService;
import com.credithc.customers.base.service.IBasePreCustomerService;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.base.utils.*;
import com.credithc.customers.base.vo.CustOauthTokenVo;
import com.credithc.customers.base.vo.LoginFlowVo;
import com.credithc.customers.base.vo.PreCustomerDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Date;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Title:
 * @Author: Denghx
 * @Date: 2020/1/13 17:54
 * @Description: com.credithc.customers.api.service.impl
 * @Version: V1.0.0
 */
@Service
@Slf4j
public class CustomerUnifyServiceImpl implements ICustomerUnifyService {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private MessageFactory messageFactory;
    @Autowired
    private CustomerExtendMapper customerExtendMapper;
    @Autowired
    private PreCustomerPassMapper preCustomerPassMapper;
    @Autowired
    private IBasePreCustomerService basePreCustomerService;
    @Autowired
    private PreCustomerMapper preCustomerMapper;
    @Autowired
    private CustomerUnifyMapper customerUnifyMapper;
    @Autowired
    private UnifySmsMapper unifySmsMapper;
    @Autowired
    private CustomerManageInfoMapper customerManageInfoMapper;
    @Autowired
    private CustomerContactInfoMapper customerContactInfoMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CustomerIdInfoMapper customerIdInfoMapper;
    @Autowired
    private OauthTokenMapper oauthTokenMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PropertiesConfig propertiesConfig;
    @Autowired
    private IBaseCustomerService baseCustomerService;
    @Autowired
    private CompanyIdInfoMapper companyIdInfoMapper;
    @Autowired
    private CompanyModifyFlowMapper companyModifyFlowMapper;
    @Autowired
    private UnifySmsPwdMapper pwdFlowMapper;
    @Autowired
    private PreCustomerUnifyLoginMapper loginFlowMapper;

    @Override
    public void forgetPwd(BaseRequest<UnifyPwdRo> request) {
        UnifyPwdRo ro = request.getBody();
        String phone = ro.getPhone();
        String password = ro.getPassword();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        log.info("【忘记/修改密码】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参phone:{},requestNo:{}", phone, ro.getRequestNo());
        try {
            //参数校验
            UnifyPwdRo.checkBaseParam(ro);
            //目前仅支持HSH与FORTUNEC
            if (!("HSH".equals(subSystemSign) || "FORTUNEC".equals(subSystemSign))) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "当前系统暂不支持，请联系管理员");
            }
            //检查用户是否已注册
            List<PreCustomerDetailVo> vos = preCustomerMapper.getPreInfo(phone, subSystemSign);
            if (vos == null || vos.size() == 0) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "该手机号未注册，请返回登录/注册页面进行注册！");
            }
            String preCustomerNo = vos.get(0).getPreCustomerNo();
            //判断用户是否设置密码，若没有则新增，有则修改
            PreCustomerPasswdPo passwdPo = commonService.getPasswd(phone, preCustomerNo, systemSign, subSystemSign, CustomerConstants.STATUS_SUCCESS);
            if (passwdPo == null) {
                commonService.insertPasswd(phone, preCustomerNo, systemSign, subSystemSign, password, CustomerConstants.STATUS_SUCCESS);
            } else {
                commonService.updatePasswdById(passwdPo.getId(), password, "修改密码");
                //清零解锁锁定状态（222累计十次锁定）
                unlock(subSystemSign, phone, 2, "222", getCurrentTimeAndTomorrow());
            }
            log.info("【忘记/修改密码】接口>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>手机:{}设置密码成功", phone);
        } catch (CustomerException e) {
            log.error("【忘记/修改密码】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }

    }

    public void unlock(String subSystemSign, String phone, Integer status, String password, List<String> time) {
        try {
            Example example = new Example(PreCustomerUnifyLoginFlowPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("phone", phone);
            criteria.andEqualTo("status", status);
            criteria.andEqualTo("subSystemSign", subSystemSign);
            criteria.andEqualTo("password", password);
            criteria.andBetween("createTime", time.get(0), time.get(1));
            PreCustomerUnifyLoginFlowPo po = new PreCustomerUnifyLoginFlowPo();
            po.setPassword("0");
            po.setRemark("修改密码后去除锁定");
            loginFlowMapper.updateByExampleSelective(po, example);
        } catch (Exception e) {
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }

    }

    @Override
    public Map<String, Object> unifyRegister(BaseRequest<CustomerUnifyRegisterRo> request) {
        log.info("【用户注册】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        try {
            //参数校验
            CustomerUnifyRegisterRo.checkBaseParam(request.getBody());
            commonService.checkRepeatRequestNo(request.getBody().getRequestNo(), TableEnum.UNIFY_REGISTER_CUSTOMER_FLOW);
            String phone = request.getBody().getPhone();
            String smsCode = request.getBody().getSmsCode();
            String subSystemSign = request.getSubSystemSign();
            boolean isCorrect = verifySmsCode(subSystemSign, phone, smsCode);
            Map<String, Object> map = new HashMap<>(2);
            Map<String, Object> resMap = new HashMap<>(2);
            if (isCorrect) {
                //验证码通过
                Map<String, Object> preMap = unifyRegisterPre(request);
                if (preMap.containsKey("msg")) {
                    map.put("msg", preMap.get("msg"));
                    map.put("code", preMap.get("code"));
                } else {
                    String preCustNo = preMap.get("preCustomerNo").toString();
                    //生成code
                    String code = unifyLoginCode(preCustNo, request.getSystemSign(), request.getSubSystemSign());
                    resMap.put("requestNo", request.getBody().getRequestNo());
                    resMap.put("code", code);
                    map.put("resMap", resMap);
                }
            } else {
                //验证码未通过
                map.put("msg", "验证码校验未通过");
                map.put("code", "2");
            }
            return map;
        } catch (CustomerException e) {
            log.error("【用户注册】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            commonService.insertCustUnifyRegisterFlow(request.getBody().getPhone(), request.getSystemSign(), request.getSubSystemSign(), request.getBody().getRequestNo(), CustomerConstants.STATUS_FAIL, StringUtils.isNotBlank(e.getMsg()) ? e.getMsg() : messageFactory.getInstance(e.getCode()).getMsg(), request.getBody().getPassword());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    private String unifyLoginCode(String preCustNo, String systemSign, String subSystemSign) {
        //查询cust_oauth_token表
        String code = UUIDUtils.getUUID();
        CustOauthTokenPo po = commonService.getOauthCode(preCustNo, subSystemSign);
        if (po != null) {
            //更新
            commonService.updateCustOauthToken(preCustNo, subSystemSign, code, null, CustomerConstants.REGISTER_STATUS, "");
        } else {
            //新增
            commonService.insertCustOauthToken(preCustNo, systemSign, subSystemSign, code, null, CustomerConstants.REGISTER_STATUS, "");
        }
        return code;
    }

    private Map<String, Object> unifyRegisterPre(BaseRequest<CustomerUnifyRegisterRo> request) {
        CustomerUnifyRegisterRo registerRo = request.getBody();
        String requestNo = registerRo.getRequestNo();
        String phone = registerRo.getPhone();
        String password = registerRo.getPassword();
        String contactType = CustomerConstants.CONTACT_TYPE_MOBILE;
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        Map<String, Object> map = new HashMap<>(2);
        PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(contactType, phone);
        String registPreCustomerNo = null;
        if (preCustomerInfoPo != null) {
            String preCustomerNo = preCustomerInfoPo.getPreCustomerNo();
            registPreCustomerNo = preCustomerInfoPo.getPreCustomerNo();
            List<CustomerExtendPo> registerList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 1);
            List<CustomerExtendPo> register4DeleteList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 6);
            if (registerList.size() > 0) {
                map.put("code", 1);
                map.put("msg", "当前注册用户已存在");
            } else if (registerList.size() == 0 && register4DeleteList.size() > 0) {
                //新增密码表
                if (StringUtils.isNotBlank(password)) {
                    commonService.insertPreCustomerPass(preCustomerNo, systemSign, subSystemSign, password, phone);
                }
                //如果此用户已存在且为注销状态，将注销状态变为正常状态，6--->1
                commonService.updateCustExtendById(register4DeleteList.get(0).getId(), 1);
                log.info("以下用户由注销状态转为未注销状态，手机号：" + phone);
                registPreCustomerNo = preCustomerNo;
            } else {
                Map<String, Object> registerInfo = createPre(request);
                //registerInfos.add(registerInfo);
                registPreCustomerNo = registerInfo.get("preCustomerNo").toString();
            }
        } else {
            Map<String, Object> registerInfo = createPre(request);
            registPreCustomerNo = registerInfo.get("preCustomerNo").toString();
            //registerInfos.add(registerInfo);
        }
        //resMap.put("requestNo", requestNo);
        //resMap.put("responseData", registerInfos);
        map.put("preCustomerNo", registPreCustomerNo);
        commonService.insertCustUnifyRegisterFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_SUCCESS, null, password);
        return map;
    }

    @Override
    public Map<String, Object> createPre(BaseRequest<CustomerUnifyRegisterRo> request) {
        log.info("新用户创建用户号开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        try {
            CustomerUnifyRegisterRo registerRo = request.getBody();
            String requestNo = registerRo.getRequestNo();
            String phone = registerRo.getPhone();
            String password = registerRo.getPassword();
            String systemSign = request.getSystemSign();
            String subSystemSign = request.getSubSystemSign();
            //参数校验
            Map<String, Object> map = new HashMap<>(2);
            BaseRequest<PreCustomerRo> preRequest = new BaseRequest<>();
            PreCustomerRo ro = new PreCustomerRo();
            ro.setRequestNo(requestNo);
            ro.setContactInfo(phone);
            ro.setContactType(CustomerConstants.CONTACT_TYPE_MOBILE);
            ro.setPassword(password);
            preRequest.setRequestTimestamp(request.getRequestTimestamp());
            preRequest.setSystemSign(systemSign);
            preRequest.setSubSystemSign(subSystemSign);
            preRequest.setSignature(request.getSignature());
            preRequest.setBody(ro);
            //统一注册用户创建用户号并且保存密码密码表
            Map<String, String> preMap = basePreCustomerService.createUnifyPreCustomerNo(preRequest);
            map.put("systemSign", systemSign);
            map.put("subSystemSign", subSystemSign);
            map.put("preCustomerNo", preMap.get("preCustomerNo"));
            return map;
        } catch (CustomerException e) {
            log.info("创建用户号失败" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }


    @Override
    public Map<String, Object> unifyRegisterLogin(BaseRequest<UnifyRegisterLoginRo> request) {
        log.info("[统一登录]注册/登录接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        UnifyRegisterLoginRo ro = request.getBody();
        String requestNo = ro.getRequestNo();
        String mobile = ro.getPhone();
        String password = ro.getPassword();
        String smsCode = ro.getSmsCode();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        try {
            //参数校验
            UnifyRegisterLoginRo.checkBaseParam(ro);
            //检查入参用户客户是否存在
            List<PreCustomerPasswdPo> pos = preCustomerPassMapper.getUnifyInfo(mobile, subSystemSign, systemSign);
            Map<String, Object> map = new HashMap<>(2);
            Map<String, Object> resMap = new HashMap<>(2);
            //用户已注册
            if (pos != null && pos.size() > 0) {
                //todo 调用登陆接口
                //调用注册接口
                BaseRequest<CustomerUnifyLoginRo> preLoginRequest = new BaseRequest<>();
                CustomerUnifyLoginRo unifyLoginRo = new CustomerUnifyLoginRo();
                unifyLoginRo.setRequestNo(requestNo);
                unifyLoginRo.setPhone(mobile);
                unifyLoginRo.setPassword(password);
                unifyLoginRo.setSmsCode(smsCode);
                preLoginRequest.setRequestTimestamp(request.getRequestTimestamp());
                preLoginRequest.setSystemSign(systemSign);
                preLoginRequest.setSubSystemSign(subSystemSign);
                preLoginRequest.setSignature(request.getSignature());
                preLoginRequest.setBody(unifyLoginRo);
                resMap = unifyLogin(preLoginRequest);

            } else {
                //调用注册接口
                BaseRequest<CustomerUnifyRegisterRo> preRequest = new BaseRequest<>();
                CustomerUnifyRegisterRo unifyRegisterRo = new CustomerUnifyRegisterRo();
                unifyRegisterRo.setRequestNo(requestNo);
                unifyRegisterRo.setPhone(mobile);
                unifyRegisterRo.setPassword(password);
                preRequest.setRequestTimestamp(request.getRequestTimestamp());
                preRequest.setSystemSign(systemSign);
                preRequest.setSubSystemSign(subSystemSign);
                preRequest.setSignature(request.getSignature());
                preRequest.setBody(unifyRegisterRo);
                resMap = unifyRegister(preRequest);
            }
            //map.put("requestNo", requestNo);
            map.put("resMap", resMap.get("resMap"));
            if (resMap.containsKey("msg")) {
                map.put("msg", resMap.get("msg"));
                map.put("code", resMap.get("code"));
            }
            return map;
        } catch (CustomerException e) {
            log.error("[统一登录]注册/登录接口信息异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }

    }

    @Override
    public Map<String, Object> sendSmsCode(BaseRequest<UnifySmsCodeRo> request) {
        log.info("【统一登录-发送验证码】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        UnifySmsCodeRo ro = request.getBody();
        String requestNo = ro.getRequestNo();
        String mobile = ro.getPhone();
        String ip = ro.getIp();
        String graphicCode = ro.getGraphicCode();
        String graphicKey = ro.getGraphicKey();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        Integer content;
        try {
            UnifySmsCodeRo.checkBaseParam(ro);
            checkUnifyParam(systemSign, subSystemSign);
            Map<String, Object> map = new HashMap<>(2);
            Map<String, Object> resMap = new HashMap<>(2);
            resMap.put("requestNo", requestNo);
            //todo 手机号139不发三方挡板
            //是否超数 0-正常状态
            String time = "0";
            //todo 当在配置手机号白名单内时，不限制发送额度
            Map<String, String> whiteListDictMap = DictionaryFactory.Dict.UNIFY_WHITE_LIST.getDictMap();
            String whiteListRule = whiteListDictMap.get("HSH");
            if (StringUtils.isNotBlank(whiteListRule) && whiteListRule.contains(mobile)) {
            } else {
                time = isToSendSmsCode(mobile, subSystemSign, ip);
            }
            //判断是否进行图形验证码校验
            if (StringUtils.isNotBlank(graphicCode) && StringUtils.isNotBlank(graphicKey)) {
                //进行图形验证
                UnifygraphicRo graphicRo = new UnifygraphicRo();
                graphicRo.setGraphicCode(graphicCode);
                graphicRo.setGraphicKey(graphicKey);
                graphicRo.setSubSystemSign(subSystemSign);
                graphicRo.setSysytemSign(systemSign);
                Map<String, Object> res = graphicVerify(graphicRo);
                if (!(boolean) res.get("checked")) {
                    //获取图形验证码
                    Map<String, Object> graphicMap1 = getRandomCodeBase64();
                    resMap.put("graphicUrl", graphicMap1.get("graphicUrl"));
                    resMap.put("graphicKey", graphicMap1.get("graphicKey"));
                    map.put("resMap", resMap);
                    map.put("msg", "图形验证码校验未通过");
                    map.put("code", "3000");
                    return map;
                } else {
                    if (time.length() > 1) {
                        throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "该手机号当天已超额，请于" + time + "后发送");
                    }
                }
            } else {
                //增加发送次数限制
                if (!time.equals("0")) {
                    if (time.equals("1") || time.equals("2")) {
                        //获取图形验证码
                        Map<String, Object> graphicMap = getRandomCodeBase64();
                        resMap.put("graphicUrl", graphicMap.get("graphicUrl"));
                        resMap.put("graphicKey", graphicMap.get("graphicKey"));
                        map.put("resMap", resMap);
                        if (time.equals("1")) {
                            map.put("msg", "该ip：" + ip + "十分钟内发送验证码超过五次");
                            map.put("code", "3001");
                        } else {
                            map.put("msg", "该手机号发送验证码每十分钟内超过两次");
                            map.put("code", "3002");
                        }
                        return map;
                    } else {
                        throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "该手机号当天已超额，请于" + time + "后发送");
                    }
                }
            }
            //生成验证码
            content = (int) ((Math.random() * 9 + 1) * 100000);
            //发送短信验证码
            commonService.sendSms(mobile, content.toString(), systemSign, subSystemSign, CustomerConstants.SMS_TEMPLATE_YZM);
            commonService.insertCustUnifySmsFlow(mobile, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_SUCCESS, null, content.toString(), ip);
            map.put("resMap", resMap);
            return map;
        } catch (CustomerException e) {
            commonService.insertCustUnifySmsFlow(mobile, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_FAIL, StringUtils.isNotBlank(e.getMsg()) ? e.getMsg() : messageFactory.getInstance(e.getCode()).getMsg(), null, ip);
            log.error("【统一登录-发送验证码】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }

    }

    @Override
    public Map<String, Object> unifyLogin(BaseRequest<CustomerUnifyLoginRo> request) {
        log.info("统一登录开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        try {
            CustomerUnifyLoginRo ro = request.getBody();
            String phone = ro.getPhone();
            String password = ro.getPassword();
            String smsCode = ro.getSmsCode();
            String systemSign = request.getSystemSign();
            String subSystemSign = request.getSubSystemSign();
            String requestNo = ro.getRequestNo();
            //把密码去掉
            ro.setPassword("******");
            request.setBody(ro);
            CustomerUnifyLoginRo.checkBaseParam(ro);
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> mapAll = new HashMap<>();
            map.put("requestNo", requestNo);
            commonService.checkRepeatRequestNo(request.getBody().getRequestNo(), TableEnum.UNIFY_LOGIN_CUSTOMER_FLOW);
            List<PreCustomerDetailVo> preCustomerDetailVoList = preCustomerMapper.getPreInfo(phone, subSystemSign);
            if (preCustomerDetailVoList != null && preCustomerDetailVoList.size() > 0) {
                PreCustomerDetailVo cust = preCustomerDetailVoList.get(0);
                PreCustomerPasswdPo condition = new PreCustomerPasswdPo();
                condition.setMobile(phone);
                condition.setSubSystemSign(request.getSubSystemSign());
                PreCustomerPasswdPo pass = preCustomerPassMapper.selectOne(condition);
                //是否让登录
                if (pass == null) {
                    //没有密码
                    mapAll.put("msg", "密码为空");
                    mapAll.put("code", 1001);
                } else {
                    /*int time = isToLogin(pass);
                    if (time < 0) {*/
                    //正常状态 校验密码
                    if (smsCode != null) {
                        //验证码登陆
                        boolean isCorrect = verifySmsCode(subSystemSign, phone, smsCode);
                        if (isCorrect) {
                            //responseMap.put("preCustomerNo", cust.getPreCustomerNo());
                            //responseMap.put("state", cust.getStatus());
                            //responseMap.put("user",userData);
                            String code = unifyLoginCode(cust.getPreCustomerNo(), request.getSystemSign(), request.getSubSystemSign());
                            map.put("code", code);
                            commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_SUCCESS, null, password, smsCode, code);
                        } else {
                            //验证码错误
                            mapAll.put("msg", "验证码错误");
                            mapAll.put("code", 1002);
                            commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_FAIL, null, password, smsCode, null);
                        }
                    } else {
                        String passwd = pass.getPasswd();
                        if (passwd.equals(EncryptUtils.getYztSha1(password))) {
                            //密码正确 返回数据
                            String code = unifyLoginCode(cust.getPreCustomerNo(), request.getSystemSign(), request.getSubSystemSign());
                            map.put("code", code);
                            commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_SUCCESS, null, password, smsCode, code);
                        } else {
                            //密码错误
                            mapAll.put("msg", "密码错误");
                            mapAll.put("code", 1003);
                            commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_FAIL, null, password, smsCode, null);
                            checkAndHandlePre(pass);
                        }
                    }
                }
            } else {
                //系统不存在该用户
                mapAll.put("msg", "该用户不存在,请核对登录名!");
                mapAll.put("code", 1005);
            }
            mapAll.put("resMap", map);
            return mapAll;
        } catch (CustomerException e) {
            log.error("统一登录异常>>>{}", e.getMsg());
            //记录登录流水
            commonService.insertCustUnifyLoginFlow(request.getBody().getPhone(), request.getSystemSign(), request.getSubSystemSign(), request.getBody().getRequestNo(), CustomerConstants.STATUS_FAIL, null, request.getBody().getPassword(), request.getBody().getSmsCode(), null);
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    public int isToLogin(PreCustomerPasswdPo pass) {
        if (pass.getLockState() == 1) {
            //正常状态
            return -1;
        } else {
            //锁定状态
            return checkAndHandlePre(pass);
        }
    }

    public int checkAndHandlePre(PreCustomerPasswdPo po) {
        Map<String, String> loginRuleDictMap = DictionaryFactory.Dict.UNIFY_LOGIN_RULE.getDictMap();
        String[] rule = loginRuleDictMap.get("HSH").split("/");
        CustomerUnifyLoginFlowRo ro = new CustomerUnifyLoginFlowRo();
        int lockTime = Integer.parseInt(rule[2]);
        ro.setHour(Integer.valueOf(rule[1]));
        ro.setNumber(Integer.valueOf(rule[0]));
        ro.setPhone(po.getMobile());
        ro.setSubSystemSign(po.getSubSystemSign());
        List<PreCustomerUnifyLoginFlowPo> recentlyList = customerUnifyMapper.getUnifyLoginFlowRecently(ro);
        if (po.getLockState() == null || po.getLockState() == 1) {
            //正常状态，检查是否需要加锁
            boolean isSuccess = false;
            if (recentlyList != null && recentlyList.size() == 5) {
                for (PreCustomerUnifyLoginFlowPo customerUnifyLoginFlowPo : recentlyList) {
                    if (customerUnifyLoginFlowPo.getStatus() == 1) {
                        isSuccess = true;
                        break;
                    }
                }
            } else {
                isSuccess = true;
            }
            if (!isSuccess) {
                //锁定账户
                po.setLockState(2);
                preCustomerPassMapper.updateByPrimaryKey(po);
                return lockTime;
            } else {
                return -1;
            }
        } else {
            //锁定状态，检查是否需要解锁
            if (recentlyList != null && recentlyList.size() > 0) {
                Timestamp timestamp = recentlyList.get(0).getCreateTime();
                Long minute = (System.currentTimeMillis() - timestamp.getTime()) / 60000;
                if (minute.intValue() < lockTime) {
                    //锁定时间以内,接着锁定
                    return lockTime - minute.intValue();
                } else {
                    //超过锁定时间，解锁
                    po.setLockState(1);
                    preCustomerPassMapper.updateByPrimaryKey(po);
                    return -1;
                }
            } else {
                //一小时内无登录记录，解锁并且让其登录
                po.setLockState(1);
                preCustomerPassMapper.updateByPrimaryKey(po);
                return -1;
            }
        }

    }


    @Override
    public Map<String, Object> cancel(BaseRequest<UnifyCancelRo> request) {
        log.info("【统一登录-用户注销】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        Map<String, Object> map = new HashMap<>();
        UnifyCancelRo ro = request.getBody();
        String phone = ro.getPhone();
        String requestNo = ro.getRequestNo();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        Integer status = CustomerConstants.STATUS_SUCCESS;
        String errorMsg = null;
        String preCustomerNo = null;
        String customerNo = null;
        try {
            //校验参数
            UnifyCancelRo.checkBaseParam(ro);
            List<PreCustomerDetailVo> vos = preCustomerMapper.getPreInfo(phone, subSystemSign);
            if (vos != null && vos.size() > 0) {
                CustomerExtendPo extendPo = new CustomerExtendPo();
                extendPo.setCustomerNo("");
                extendPo.setStatus(6);
                extendPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                extendPo.setId(vos.get(0).getExtendId());
                customerExtendMapper.updateByPrimaryKeySelective(extendPo);
                Map<String, Object> responseData = new HashMap<>();
                preCustomerNo = vos.get(0).getPreCustomerNo();
                customerNo = vos.get(0).getCustomerNo();
                responseData.put("systemSign", systemSign);
                responseData.put("subSystemSign", subSystemSign);
                responseData.put("preCustomerNo", preCustomerNo);
                responseData.put("customerNo", customerNo);
                map.put("responseData", responseData);
                //更新code表
                CustOauthTokenPo po = commonService.getOauthCode(preCustomerNo, subSystemSign);
                if (po != null) {
                    po.setRegisterStatus(CustomerConstants.UNREGISTER_STATUS);
                    po.setModifyTime(new Timestamp(System.currentTimeMillis()));
                    oauthTokenMapper.updateByPrimaryKeySelective(po);
                }
                //todo 未测试上线
                if (CustomerConstants.YZT.equalsIgnoreCase(systemSign)) {
                    //更新渠道表授权状态为2-无效
                    commonService.updateChannelByCancel(preCustomerNo, systemSign, subSystemSign, 2, "用户注销");
                    //更改用户邀请码为无效
                    commonService.updateInvitationCode(preCustomerNo, systemSign, subSystemSign, 2, "用户注销");
                    //用户被邀请人身份失效，邀请人身份暂不处理
                    commonService.updateInvitationRelation(preCustomerNo, systemSign, subSystemSign, 2, "被邀请人身份记录注销");
                    //用户密码失效
                    commonService.updatePasswdByCancel(phone, systemSign, subSystemSign, 2, "用户注销");
                }
            } else {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "用户不存在");
            }
            map.put("requestNo", requestNo);
            return map;
        } catch (CustomerException e) {
            status = CustomerConstants.STATUS_FAIL;
            errorMsg = e.getMsg();
            log.error("【统一登录-用户注销】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        } finally {
            commonService.insertCustCancelFlow(phone, systemSign, subSystemSign, requestNo, status, errorMsg, preCustomerNo, customerNo);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> modifyPhone(BaseRequest<UnifyModifyPhoneRo> bRequest) {
        log.info("【统一登录-用户修改手机号】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", bRequest);
        try {
            UnifyModifyPhoneRo ro = bRequest.getBody();
            UnifyModifyPhoneRo.checkBaseParam(ro);
            String oldPhone = ro.getOldPhone();
            String systemSign = bRequest.getSystemSign();
            String subSystemSign = bRequest.getSubSystemSign();
            String newPhone = ro.getNewPhone();
            String newPreCustomerNo = null;
            String oldPreCustomerNo = null;
            //查询旧数据
            List<PreCustomerDetailVo> oldPreInfos = preCustomerMapper.getPreInfo(oldPhone, subSystemSign);
            List<PreCustomerDetailVo> newPreInfos = preCustomerMapper.getPreInfoOnly(newPhone);
            List<PreCustomerDetailVo> tmpPreInfos = preCustomerMapper.getPreInfoOnly(oldPhone);
            if (oldPreInfos != null && oldPreInfos.size() > 0) {
                PreCustomerDetailVo oldPreInfo = oldPreInfos.get(0);
                oldPreCustomerNo = oldPreInfo.getPreCustomerNo();
                if (newPreInfos != null && newPreInfos.size() > 0) {
                    for (PreCustomerDetailVo vo : newPreInfos) {
                        if (vo.getSubSystemSign().equals(subSystemSign)) {
                            //在当前系统下新手机号已经注册过
                            throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "新手机号在当前系统已注册!");
                        }
                    }
                    //更新扩展表
                    newPreCustomerNo = newPreInfos.get(0).getPreCustomerNo();
                    updateCustomerExtend(oldPreInfo.getExtendId(), newPreCustomerNo);
                    commonService.updateTokenByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                    commonService.updateChannelByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                } else {
                    //新手机号未注册，且旧手机号只有当前系统使用中，直接更新cust_pre_info表;旧手机号多个系统使用则需要新生成用户号
                    if (tmpPreInfos != null && tmpPreInfos.size() == 1) {
                        //如果新手机号已注销，可以修改
                        PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(CustomerConstants.CONTACT_TYPE_MOBILE, newPhone);
                        if (preCustomerInfoPo != null) {
                            newPreCustomerNo = preCustomerInfoPo.getPreCustomerNo();
                            //更新数据
                            updateCustomerExtend(oldPreInfo.getExtendId(), newPreCustomerNo);
                            commonService.updateTokenByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                            commonService.updateChannelByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                        } else {
                            commonService.updateCustPreInfo(oldPreInfo.getId(), newPhone);
                            newPreCustomerNo = tmpPreInfos.get(0).getPreCustomerNo();
                        }
                    } else {
                        //创建新用户
                        PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(CustomerConstants.CONTACT_TYPE_MOBILE, newPhone);
                        if (preCustomerInfoPo == null) {
                            newPreCustomerNo = CustomerUtils.generatePreCustomerNo();
                            commonService.insertCustPreInfo(newPreCustomerNo, newPhone);
                        } else {
                            newPreCustomerNo = preCustomerInfoPo.getPreCustomerNo();
                        }
                        //更新数据
                        updateCustomerExtend(oldPreInfo.getExtendId(), newPreCustomerNo);
                        commonService.updateTokenByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                        commonService.updateChannelByPre(newPreCustomerNo, subSystemSign, oldPreCustomerNo);
                    }
                }
            } else {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "修改手机号不存在");
            }
            //若用户密码存在，同步修改密码
            if (CustomerConstants.YZT.equalsIgnoreCase(systemSign)) {
                commonService.updatePasswdByModify(oldPhone, newPhone, newPreCustomerNo, systemSign, subSystemSign, "修改手机号同步密码");
            }
            //返回数据结构
            Map<String, Object> map = new HashMap<>();
            map.put("requestNo", ro.getRequestNo());
            map.put("oldPreCustomerNo", oldPreCustomerNo);
            map.put("newPreCustomerNo", newPreCustomerNo);
            return map;
        } catch (CustomerException e) {
            log.error("【统一登录-用户修改手机号】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    public void updateCustomerExtend(String id, String newPreCustomerNo) {
        try {
            CustomerExtendPo po = new CustomerExtendPo();
            po.setId(id);
            po.setPreCustomerNo(newPreCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            po.setRemark("统一登录-手机号修改");
            customerExtendMapper.updateByPrimaryKeySelective(po);
        } catch (DataAccessException e) {
            log.error("【统一登录-用户修改手机号】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    private boolean verifySmsCode(String subSystemSign, String phone, String smsCode) {
        UnifySmsCodeFlowPo po = unifySmsMapper.getUnifySmsCodeRecently(subSystemSign, phone, smsCode);
        return po != null;
    }

    private boolean verifyPassNum(String subSystemSign, String phone) {
        //判断当天是否超频
        List<LoginFlowVo> list = commonService.getCustomerUnifyLoginFlowList(subSystemSign, phone, 2, "222", getCurrentTimeAndTomorrow());
        if (list != null && list.size() > 9) {
            //错误次数超过十次
            /*String lastTime = list.get(0).getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (pass != null && pass.getUpdateTime() != null) {
                try {
                    long narginTime = pass.getUpdateTime().getTime() - sdf.parse(lastTime).getTime();
                    if (narginTime > 0) {
                        //错误后修改过
                    } else {
                        throw new CustomerException(555, "当日密码错误超过十次");
                    }
                } catch (ParseException e) {
                    throw new CustomerException(444, "日期转换错误");
                }
            }*/
            throw new CustomerException(555, "密码错误次数过多,请24点后重新尝试!");
        }
        return true;
    }

    private boolean verifyPassWord(String subSystemSign, String phone, String password, List<PreCustomerDetailVo> preCustomerDetailVoList) {
        PreCustomerPasswdPo condition = new PreCustomerPasswdPo();
        condition.setMobile(phone);
        condition.setSubSystemSign(subSystemSign);
        condition.setLockState(1);
        PreCustomerPasswdPo pass = preCustomerPassMapper.selectOne(condition);
        //判断当天是否超频
        //List<LoginFlowVo> list = commonService.getCustomerUnifyLoginFlowList(subSystemSign,phone,2, "222",getCurrentTimeAndTomorrow());
        //if (list !=null && list.size() > 9) {
        //错误次数超过十次
            /*String lastTime = list.get(0).getCreateTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (pass != null && pass.getUpdateTime() != null) {
                try {
                    long narginTime = pass.getUpdateTime().getTime() - sdf.parse(lastTime).getTime();
                    if (narginTime > 0) {
                        //错误后修改过
                    } else {
                        throw new CustomerException(555, "当日密码错误超过十次");
                    }
                } catch (ParseException e) {
                    throw new CustomerException(444, "日期转换错误");
                }
            }*/
        // throw new CustomerException(555, "密码错误次数过多,请24点后重新尝试!");
        //}
        //是否让登录
        if (pass == null) {
            //没有密码
            if (preCustomerDetailVoList != null && preCustomerDetailVoList.size() > 0) {
                throw new CustomerException(111, "密码错误,请重新尝试!");
            } else {
                throw new CustomerException(333, "该手机号未注册,请返回登陆/注册页面进行注册!");
            }
        } else {
            String passwd = pass.getPasswd();
            if (passwd.equals(EncryptUtils.getYztSha1(password))) {
                //密码正确 返回数据
                return true;
            } else {
                //密码错误
                throw new CustomerException(222, "密码错误,请重新尝试!");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> changeInfo(BaseRequest<CustomerUnifyUpdateRo> bRequest) {
        log.info("用户信息变更开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            CustomerUnifyUpdateRo ro = bRequest.getBody();
            CustomerUnifyUpdateRo.checkBaseParam(ro);
            commonService.checkRepeatRequestNo(ro.getRequestNo(), TableEnum.UNIFY_UPDATE_CUSTOMER_FLOW);
            if (StringUtils.isNotBlank(ro.getAccessToken())) {
                CustOauthTokenVo vo = commonService.getOauthTokenInfo(ro.getAccessToken(), bRequest.getSubSystemSign());
                if (vo == null) {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "token无效!");
                }
                ro.setPreCustomerNo(vo.getPreCustomerNo());
                ro.setCustomerNo(vo.getCustomerNo());
            }
            String customerNo = ro.getCustomerNo();
            Map<String, Object> map = new HashMap<>();
            //查询用户号与客户号是否存在
            CustomerExtendPo extendPo = commonService.getExistCustomerExtend(ro.getPreCustomerNo(), customerNo, bRequest.getSystemSign(), bRequest.getSubSystemSign());
            if (extendPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户号不存在!");
            }
            PreCustomerInfoPo preCustomerInfoParam = new PreCustomerInfoPo();
            preCustomerInfoParam.setPreCustomerNo(extendPo.getPreCustomerNo());
            //判断三要素是否存在HYR/HHR
            CustomerUnifyUpdateRo param2 = new CustomerUnifyUpdateRo();
            param2.setCustomerNo(null);
            param2.setSubSystemSign(null);
            param2.setIdCardNo(ro.getIdCardNo());
            param2.setCustomerName(ro.getCustomerName());
            param2.setIdCardType(ro.getIdCardType());
            List<HashMap<String, Object>> existDataList = customerUnifyMapper.getCustomerNoSubSystemSign(param2);
            String updateCustomerNo = null;
            map.put("requestNo", ro.getRequestNo());
            if (existDataList != null && existDataList.size() > 0) {
                StringBuffer subSystemSigns = new StringBuffer();
                for (HashMap<String, Object> stringObjectHashMap : existDataList) {
                    subSystemSigns.append(stringObjectHashMap.get("subSystemSign").toString());
                    subSystemSigns.append(stringObjectHashMap.get("status").toString());
                }
                String sys = bRequest.getSubSystemSign() + "1";
                if (subSystemSigns.toString().indexOf(sys) != -1) {
                    //包含
                    throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "三要素存在于当前系统，无法修改");
                } else {
                    //存在于其他系统或者当前系统但状态不为上述情况
                    updateCustomerNo = existDataList.get(0).get("customerNo").toString();
                    CustomerManageInfoPo tempPo = new CustomerManageInfoPo();
                    tempPo.setCustomerNo(updateCustomerNo);
                    List<CustomerManageInfoPo> tempPos = customerManageInfoMapper.select(tempPo);
                    if (tempPos != null && tempPos.size() > 0) {
                        for (CustomerManageInfoPo manageInfoPo : tempPos) {
                            if (manageInfoPo.getSubSystemSign().equals(bRequest.getSubSystemSign())) {
                                map.put("customerNo", updateCustomerNo);
                                updateCustomerExtend(bRequest.getSystemSign(), bRequest.getSubSystemSign(), customerNo, updateCustomerNo);
                                //插入contact
                                updateCustomerContact(bRequest.getSystemSign(), bRequest.getSubSystemSign(), customerNo, updateCustomerNo);
                                commonService.insertCustUnifyUpdateFlow(bRequest.toString(), bRequest.getSystemSign(), bRequest.getSubSystemSign(), bRequest.getBody().getRequestNo(), CustomerConstants.STATUS_SUCCESS, "");
                                return map;
                            }
                        }

                    }
                }
            } else {
                //不存在该三要素
                updateCustomerNo = CustomerUtils.generatePersonalCustomerNo();
                CustomerInfoPo po = new CustomerInfoPo();
                po.setId(UUIDUtils.getUUID());
                po.setCustomerType("1");
                po.setCustomerNo(updateCustomerNo);
                po.setCreateTime(new Timestamp(System.currentTimeMillis()));
                po.setCreateDate(new Date(System.currentTimeMillis()));
                //插入主表
                customerMapper.insert(po);
                //插入cust_id_info
                CustomerIdInfoPo idInfoPo = new CustomerIdInfoPo();
                idInfoPo.setId(UUIDUtils.getUUID());
                idInfoPo.setCustomerNo(updateCustomerNo);
                idInfoPo.setCustomerName(ro.getCustomerName());
                idInfoPo.setIdCardType(ro.getIdCardType());
                idInfoPo.setIdCardNo(ro.getIdCardNo());
                idInfoPo.setElementsVerified(CustomerConstants.STATUS_ELEMENTS_UNVERIFIED);
                idInfoPo.setCustomerProperty(CustomerConstants.CUSTOMER_PROPERTY_OFFICIAL);
                //依据子系统标识判断当前客户号对应系统
                idInfoPo.setSubSystemSign(bRequest.getSubSystemSign());
                idInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
                customerIdInfoMapper.insert(idInfoPo);
            }
            //插入cust_manage_info
            CustomerManageInfoPo manageInfoPo = new CustomerManageInfoPo();
            manageInfoPo.setCustomerNo(updateCustomerNo);
            manageInfoPo.setDate(LocalDateUtils.getLocalDateStr());
            manageInfoPo.setCreateTime(new Timestamp(System.currentTimeMillis()));
            manageInfoPo.setSubSystemSign(bRequest.getSubSystemSign());
            customerManageInfoMapper.insert(manageInfoPo);
            //插入contact
            updateCustomerContact(bRequest.getSystemSign(), bRequest.getSubSystemSign(), customerNo, updateCustomerNo);
            //更新用户-客户关联关系表
            updateCustomerExtend(bRequest.getSystemSign(), bRequest.getSubSystemSign(), customerNo, updateCustomerNo);
            map.put("customerNo", updateCustomerNo);
            //插入流水信息
            commonService.insertCustUnifyUpdateFlow(bRequest.toString(), bRequest.getSystemSign(), bRequest.getSubSystemSign(), bRequest.getBody().getRequestNo(), CustomerConstants.STATUS_SUCCESS, "");
            return map;
        } catch (CustomerException e) {
            log.error("客户修改三要素异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            commonService.insertCustUnifyUpdateFlow(bRequest.toString(), bRequest.getSystemSign(), bRequest.getSubSystemSign(), bRequest.getBody().getRequestNo(), CustomerConstants.STATUS_FAIL, e.getMsg());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    public void updateCustomerExtend(String systemSign, String subSystemSign, String oldCustomerNo, String updateCustomerNo) {
        try {
            Example example = new Example(CustomerExtendPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", oldCustomerNo);
            criteria.andEqualTo("systemSign", systemSign);
            criteria.andEqualTo("subSystemSign", subSystemSign);
            CustomerExtendPo po = new CustomerExtendPo();
            po.setCustomerNo(updateCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            po.setRemark("客户三要素修改变更");
            customerExtendMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.error("更新用户-客户信息关联表异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    public void updateCustomerContact(String systemSign, String subSystemSign, String oldCustomerNo, String updateCustomerNo) {
        try {
            Example example = new Example(CustomerContactInfoPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", oldCustomerNo);
            criteria.andEqualTo("systemSign", systemSign);
            criteria.andEqualTo("subSystemSign", subSystemSign);
            CustomerContactInfoPo po = new CustomerContactInfoPo();
            po.setCustomerNo(updateCustomerNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            po.setRemark("客户三要素修改变更");
            customerContactInfoMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.error("更新客户联系信息表异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> untie(BaseRequest<CustomerUnifyUntieRo> bRequest) {
        log.info("【统一登录-解绑】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        CustomerUnifyUntieRo ro = bRequest.getBody();
        String requestNo = ro.getRequestNo();
        String systemSign = bRequest.getSystemSign();
        String subSystemSign = bRequest.getSubSystemSign();
        Integer status = CustomerConstants.STATUS_SUCCESS;
        String errorMsg = null;
        String preCustomerNo = null;
        String customerNo = null;
        String name = null;
        String idType = null;
        String idNo = null;
        try {
            CustomerUnifyUntieRo.checkBaseParam(ro);
            Map<String, Object> map = new HashMap<>();
            map.put("requestNo", requestNo);
            if (StringUtils.isNotBlank(ro.getAccessToken())) {
                CustOauthTokenVo vo = commonService.getOauthTokenInfo(ro.getAccessToken(), subSystemSign);
                if (vo == null) {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "token无效!");
                }
                preCustomerNo = vo.getPreCustomerNo();
                customerNo = vo.getCustomerNo();
                //查询用户号与客户号是否存在
                List<CustomerExtendPo> extendPos = getCustExend(systemSign, subSystemSign, preCustomerNo, customerNo);
                if (extendPos == null || extendPos.size() == 0) {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户号不存在!");
                }
                if (extendPos.size() > 1) {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "当前客户号绑定多个用户,请指定需要解绑用户!");
                }
                //更新cust_extend表
                updateCustExend(systemSign, subSystemSign, preCustomerNo, customerNo);
                preCustomerNo = extendPos.get(0).getPreCustomerNo();
                customerNo = extendPos.get(0).getCustomerNo();
            } else {
                customerNo = ro.getCustomerNo();
                idNo = ro.getIdInfo().getIdCardNo();
                idType = ro.getIdInfo().getIdCardType();
                name = ro.getIdInfo().getCustomerName();
                CustomerIdInfoPo idInfoParam = new CustomerIdInfoPo();
                idInfoParam.setCustomerName(name);
                idInfoParam.setIdCardNo(idNo);
                if (StringUtils.isBlank(idType)) {
                    idInfoParam.setIdCardType("1");
                } else {
                    idInfoParam.setIdCardType(idType);
                }
                idInfoParam.setCustomerNo(customerNo);
                List<CustomerIdInfoPo> list = customerIdInfoMapper.select(idInfoParam);
                if (list != null && list.size() > 0) {
                    //查询客户号在当前系统下是否存在
                    List<CustomerExtendPo> extendPos = getCustExend(systemSign, subSystemSign, ro.getPreCustomerNo(), customerNo);
                    if (extendPos == null || extendPos.size() == 0) {
                        throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户号不存在!");
                    }
                    if (extendPos.size() > 1) {
                        throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "当前客户号绑定多个用户,请指定需要解绑用户!");
                    }
                    //更新
                    updateCustExend(systemSign, subSystemSign, ro.getPreCustomerNo(), customerNo);
                    preCustomerNo = extendPos.get(0).getPreCustomerNo();
                    customerNo = extendPos.get(0).getCustomerNo();
                } else {
                    throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户号与证件信息不匹配!");
                }
            }
            return map;
        } catch (CustomerException e) {
            status = CustomerConstants.STATUS_FAIL;
            errorMsg = e.getMsg();
            log.error("【统一登录-解绑】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        } finally {
            //插入流水
            commonService.insertCustUntieFlow(systemSign, subSystemSign, requestNo, status, errorMsg, preCustomerNo, customerNo, name, idType, idNo);
        }
    }

    public List<CustomerExtendPo> getCustExend(String systemSign, String subSystemSign, String preCustomerNo, String customerNo) {
        try {
            CustomerExtendPo extendParam = new CustomerExtendPo();
            extendParam.setCustomerNo(customerNo);
            if (StringUtils.isNotBlank(preCustomerNo)) {
                extendParam.setPreCustomerNo(preCustomerNo);
            }
            extendParam.setSystemSign(systemSign);
            extendParam.setSubSystemSign(subSystemSign);
            extendParam.setStatus(1);
            List<CustomerExtendPo> extendPos = customerExtendMapper.select(extendParam);
            return extendPos;
        } catch (DataAccessException e) {
            log.error("查询cust_extend异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    public void updateCustExend(String systemSign, String subSystemSign, String preCustomerNo, String customerNo) {
        try {
            Example example = new Example(CustomerExtendPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("customerNo", customerNo);
            if (StringUtils.isNotBlank(preCustomerNo)) {
                criteria.andEqualTo("preCustomerNo", preCustomerNo);
            }
            criteria.andEqualTo("systemSign", systemSign);
            criteria.andEqualTo("subSystemSign", subSystemSign);
            CustomerExtendPo po = new CustomerExtendPo();
            po.setCustomerNo("");
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            customerExtendMapper.updateByExampleSelective(po, example);
        } catch (DataAccessException e) {
            log.error("更新cust_extend异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> login(BaseRequest<CustomerUnifyLoginRo> request) {
        log.info("【登录】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", request);
        try {
            CustomerUnifyLoginRo ro = request.getBody();
            String phone = ro.getPhone();
            String password = ro.getPassword();
            String smsCode = ro.getSmsCode();
            String systemSign = request.getSystemSign();
            String subSystemSign = request.getSubSystemSign();
            String requestNo = ro.getRequestNo();
            String customerNoExsist = null;
            if (StringUtils.isBlank(smsCode) && StringUtils.isNotBlank(password)) {
                verifyPassNum(subSystemSign, phone);
            }
            CustomerUnifyLoginRo.checkBaseParam(ro);
            checkUnifyParam(systemSign, subSystemSign);
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> mapAll = new HashMap<>();
            map.put("requestNo", requestNo);
//            commonService.checkRepeatRequestNo(requestNo, TableEnum.UNIFY_LOGIN_CUSTOMER_FLOW);
            //校验手机号验证码
//            boolean isCorrect = verifySmsCode(subSystemSign,phone,smsCode);
            //todo 添加验证码666666不校验挡板
            boolean isCorrect = false;
            if (StringUtils.isNotBlank(smsCode)) {
                if (smsCode.equals("888888")) {
                    //当为配置手机号段时，发送固定短信验证码888888
                    Map<String, String> fixedCodeDictMap = DictionaryFactory.Dict.UNIFY_FIXED_CODE.getDictMap();
                    String fixedCodeRule = fixedCodeDictMap.get("HSH");
                    if (StringUtils.isNotBlank(fixedCodeRule)) {
                        String[] rule = fixedCodeRule.split("/");
                        String fixedPhone = rule[1];
                        if (fixedPhone.contains(phone)) {
                            isCorrect = true;
                        } else {
                            isCorrect = verifySmsCode(subSystemSign, phone, smsCode);
                        }
                    }
                } else {
                    isCorrect = verifySmsCode(subSystemSign, phone, smsCode);
                }
            }
            //查询用户信息
            List<PreCustomerDetailVo> preCustomerDetailVoList = preCustomerMapper.getPreInfo(phone, subSystemSign);
            if (!isCorrect && StringUtils.isNotBlank(password)) {
                //短信校验未通过，并且传入密码，启用密码校验
                isCorrect = verifyPassWord(subSystemSign, phone, password, preCustomerDetailVoList);
            }
            String preCustNo = null;
            Integer status = 1;
            boolean isMore = false;
            if (isCorrect) {
                //校验正确
                //List<PreCustomerDetailVo> preCustomerDetailVoList = preCustomerMapper.getPreInfo(phone, subSystemSign);
                if (preCustomerDetailVoList != null && preCustomerDetailVoList.size() > 0) {
                    PreCustomerDetailVo cust = preCustomerDetailVoList.get(0);
                    preCustNo = cust.getPreCustomerNo();
                    if (CustomerConstants.BDSHM.equals(subSystemSign)) {
                        //查询是否一对多
                        List<PreCustomerDetailVo> preList = customerExtendMapper.getPreCustomerCompanyDetail(preCustNo, subSystemSign, 1);
                        if (preList != null && preList.size() > 0) {
                            List<PreCustomerDetailVo> preListPer = customerExtendMapper.getPreCustomerPersonDetail(preCustNo, subSystemSign, 1);
                            if (preListPer != null && preListPer.size() > 0) {
                                preList.addAll(preListPer);
                            }
                            if (preList.size() > 1) {
                                List<Map<String, Object>> userInfos = new ArrayList<>();
                                for (PreCustomerDetailVo preCustomerDetailVo : preList) {
                                    Map<String, Object> userInfo = new HashMap<>();
                                    userInfo.put("preCustomerNo", preCustomerDetailVo.getPreCustomerNo());
                                    userInfo.put("customerNo", preCustomerDetailVo.getCustomerNo());
                                    userInfo.put("customerName", preCustomerDetailVo.getCustomerName());
                                    userInfos.add(userInfo);
                                }
                                map.put("userInfos", userInfos);
                                isMore = true;
                            }
                        }
                    }

                } else {
                    //未注册用户,BDSHM和GZTB不可通过此接口注册，只能登陆
                    if (subSystemSign.equals("BDSHM") || subSystemSign.equals("GZTB")) {
                        //extend内customerNo存在，则走子账号注册逻辑
                        if (StringUtils.isBlank(ro.getExtend())) {
                            mapAll.put("msg", "未找到用户信息，请联系管理员");
                            mapAll.put("code", 999);
                            mapAll.put("resMap", map);
                            return mapAll;
                        } else {
                            //插入extend表关联数据
                            JSONObject jsonObject = JSON.parseObject(ro.getExtend());
                            String customerNo = jsonObject.getString("customerNo");
                            if (StringUtils.isNotBlank(customerNo)) {
                                CustomerExtendPo condition = new CustomerExtendPo();
                                condition.setCustomerNo(customerNo);
                                condition.setSystemSign(systemSign);
                                condition.setSubSystemSign(subSystemSign);
                                condition.setStatus(1);
                                List<CustomerExtendPo> pos = customerExtendMapper.select(condition);
                                if (pos != null && pos.size() > 0) {
                                    customerNoExsist = customerNo;
                                    preCustNo = register(request, customerNoExsist);
                                } else {
                                    mapAll.put("msg", "未找到对应客户号信息");
                                    mapAll.put("code", 999);
                                    mapAll.put("resMap", map);
                                    return mapAll;
                                }
                            } else {
                                mapAll.put("msg", "未找到对应客户号信息");
                                mapAll.put("code", 999);
                                mapAll.put("resMap", map);
                                return mapAll;
                            }
                        }
                    } else {
                        //调用注册接口
                        preCustNo = register(request, customerNoExsist);
                    }
                    //邀请码不为空，处理邀请码逻辑
                    if (StringUtils.isNotBlank(ro.getInvitationCode())) {
                        commonService.handleInvitationCode(request, preCustNo);
                    }
                }
                //查询cust_oauth_token表
                if (isMore) {
                    //一对多
                    mapAll.put("msg", "用户存在多个客户号信息，请选择当前登录客户");
                    mapAll.put("code", 1);
                    status = 2;
                }
                String code = UUIDUtils.getUUID();
                CustOauthTokenPo po = commonService.getOauthCode(preCustNo, subSystemSign);
                if (po != null) {
                    //更新
                    commonService.updateCustOauthToken(preCustNo, request.getSubSystemSign(), code, status, CustomerConstants.REGISTER_STATUS, "");
                } else {
                    //新增
                    commonService.insertCustOauthToken(preCustNo, request.getSystemSign(), request.getSubSystemSign(), code, status, CustomerConstants.REGISTER_STATUS, "");
                }
                map.put("code", code);
                commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_SUCCESS, null, null, smsCode, code);
            } else {
                //验证码错误
                mapAll.put("msg", "验证码无效，请重新输入");
                mapAll.put("code", 1002);
                commonService.insertCustUnifyLoginFlow(phone, systemSign, subSystemSign, requestNo, CustomerConstants.STATUS_FAIL, "验证码错误", null, smsCode, null);
            }
            mapAll.put("resMap", map);
            return mapAll;
        } catch (CustomerException e) {
            log.error("【登录】异常>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", e.getMsg());
            //记录登录流水
            commonService.insertCustUnifyLoginFlow(request.getBody().getPhone(), request.getSystemSign(), request.getSubSystemSign(), request.getBody().getRequestNo(), CustomerConstants.STATUS_FAIL, e.getMsg(), String.valueOf(e.getCode()), request.getBody().getSmsCode(), null);
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    private String register(BaseRequest<CustomerUnifyLoginRo> request, String customerNoExsist) {
        BaseRequest<CustomerUnifyRegisterRo> preRequest = new BaseRequest<>();
        CustomerUnifyRegisterRo unifyRegisterRo = new CustomerUnifyRegisterRo();
        unifyRegisterRo.setRequestNo(request.getBody().getRequestNo());
        unifyRegisterRo.setPhone(request.getBody().getPhone());
        preRequest.setRequestTimestamp(request.getRequestTimestamp());
        preRequest.setSystemSign(request.getSystemSign());
        preRequest.setSubSystemSign(request.getSubSystemSign());
        preRequest.setSignature(request.getSignature());
        preRequest.setBody(unifyRegisterRo);
        Map<String, Object> resMap = unifyRegisterPre(preRequest);
        String preCustNo = resMap.get("preCustomerNo").toString();
        //插入客户号
        if (StringUtils.isNotBlank(customerNoExsist)) {
            Example example = new Example(CustomerExtendPo.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("preCustomerNo", preCustNo);
            criteria.andEqualTo("systemSign", request.getSystemSign());
            criteria.andEqualTo("subSystemSign", request.getSubSystemSign());
            CustomerExtendPo po = new CustomerExtendPo();
            po.setCustomerNo(customerNoExsist);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            customerExtendMapper.updateByExampleSelective(po, example);
        }
        return preCustNo;
    }


    @Override
    public Map<String, Object> getToken(BaseRequest<UnifyTokenRo> bRequest) {
        log.info("【code获取token信息】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            UnifyTokenRo ro = bRequest.getBody();
            UnifyTokenRo.checkBaseParam(ro);
            String code = ro.getCode();
            String requestNo = ro.getRequestNo();
            String subSystemSign = bRequest.getSubSystemSign();
            String systemSign = bRequest.getSystemSign();
            String accessToken = null;
            String refreshToken = null;
            String customerNo = null;
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(systemSign, subSystemSign);
            //查询code信息是否存在
            CustOauthTokenPo oauthTokenPo = commonService.getOauthCode(code);
            if (oauthTokenPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "code信息不存在!");
            }
            if (!subSystemSign.equals(oauthTokenPo.getSubSystemId())) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "code信息不存在!");
            }
            //type=1表示为只查询不更新token信息，仅支付服务会使用
            if (StringUtils.isNotBlank(ro.getType()) && ("1".equals(ro.getType()))) {
                accessToken = oauthTokenPo.getAccessToken();
                refreshToken = oauthTokenPo.getRefreshToken();
            } else {
                //todo 生成随机的access_token\refresh_token，并记录时间，插入表中
                accessToken = EncryptUtils.getYztSha1(code + "accessToken");
                refreshToken = EncryptUtils.getYztSha1(code + "refreshToken");
                oauthTokenPo.setAccessTokenTime(new Timestamp(System.currentTimeMillis()));
                oauthTokenPo.setAccessToken(accessToken);
                oauthTokenPo.setRefreshToken(refreshToken);
                oauthTokenMapper.updateByPrimaryKeySelective(oauthTokenPo);
            }
            String preCustomerNo = oauthTokenPo.getPreCustomerNo();
            PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(preCustomerNo);
            CustomerExtendPo customerExtendPo = commonService.getExistPreCustomerExtend(preCustomerNo, bRequest.getSystemSign(), bRequest.getSubSystemSign());
            if (customerExtendPo != null) {
                customerNo = customerExtendPo.getCustomerNo();
            }
            if (StringUtils.isNotBlank(oauthTokenPo.getCustomerNo()) && oauthTokenPo.getStatus() == 1) {
                customerNo = oauthTokenPo.getCustomerNo();
            }
            CustomerExtendPo regiesterInfo = commonService.getRegisterSystem(preCustomerNo, systemSign);
            String registerSystem = null;
            if (regiesterInfo != null) {
                registerSystem = regiesterInfo.getSubSystemSign();
            }
            String phone = preCustomerInfoPo.getContactInfo();
            map.put("accessToken", accessToken);
            map.put("refreshToken", refreshToken);
            map.put("preCustomerNo", preCustomerNo);
            map.put("phone", phone);
            map.put("requestNo", requestNo);
            map.put("customerNo", customerNo);
            map.put("systemSign", bRequest.getSystemSign());
            map.put("registerSystem", registerSystem);
            if (StringUtils.isNotBlank(oauthTokenPo.getCreditSystem())) {
                subSystemSign = oauthTokenPo.getCreditSystem();
            }
            map.put("subSystemSign", subSystemSign);
            return map;
        } catch (CustomerException e) {
            log.error("【code获取token信息】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> grantAuth(UnifyGrantAuthRo ro) {
        log.info("【授权页面请求一账通接口】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", ro);
        try {
            UnifyGrantAuthRo.checkBaseParam(ro);
            String code = ro.getCode();
            String mainSystemId = ro.getMainSystemId();
            String subSystemId = ro.getSubSystemId();
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(mainSystemId, subSystemId);
            //todo h5接口验签 UNIFY_CHECK_RULE为code验签,否则不校验
            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
            String checkRule = checkRuleDictMap.get(mainSystemId);
            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
                commonService.verifySignature(mainSystemId, ro.getTimestamp(), code, ro.getVerifyCode());
            }

            //查询code信息是否存在
            CustOauthTokenPo oauthTokenPo = commonService.getOauthCode(code);
            if (oauthTokenPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "code信息不存在!");
            }
            String preCustomerNo = oauthTokenPo.getPreCustomerNo();
            //查询cust_oauth_channel渠道表是否存在授权记录
            CustOauthChannelPo oauthChannelPo = commonService.getOauthChannel(preCustomerNo, mainSystemId, subSystemId);
            boolean granted = false;
            //status 1-已授权；2-未授权
            Integer status = 2;
            //授权状态必须为有效1，若为2无效表示已注销，需要重新授权登录流程
            if (oauthChannelPo != null && oauthChannelPo.getStatus() == 1) {
                // 更新已授权业务系统code值
                String loginCode = UUIDUtils.getUUID();
                commonService.updateCustOauthToken(preCustomerNo, subSystemId, loginCode, null, CustomerConstants.UNREGISTER_STATUS, mainSystemId);
                granted = true;
                status = 1;
                map.put("code", loginCode);
            }
            map.put("granted", granted);
            //记录授权登录流水
            commonService.insertCustOauthLoginFlow(ro.getRequestNo(), mainSystemId, subSystemId, code, preCustomerNo, status);
            return map;
        } catch (CustomerException e) {
            log.error("【授权页面请求一账通接口】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> subGrantAuth(UnifySubGrantAuthRo ro) {
        log.info("【授权接口】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", ro);
        try {
            UnifySubGrantAuthRo.checkBaseParam(ro);
            String code = ro.getCode();
            String mainSystemId = ro.getMainSystemId();
            String subSystemId = ro.getSubSystemId();
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(mainSystemId, subSystemId);
            //判断是否需要验签
            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
            String checkRule = checkRuleDictMap.get(mainSystemId);
            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
                //todo h5接口验签
                commonService.verifySignature(mainSystemId, ro.getTimestamp(), code, ro.getVerifyCode());
            }
            //查询code信息是否存在
            CustOauthTokenPo oauthTokenPo = commonService.getOauthCode(code);
            if (oauthTokenPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "code信息不存在!");
            }
            String preCustomerNo = oauthTokenPo.getPreCustomerNo();
            String systemId = CustomerConstants.YZT;
            //cust_oauth_channel渠道表新增授权记录
            CustOauthChannelPo oauthChannelPo = commonService.getOauthChannel(preCustomerNo, mainSystemId, subSystemId);
            if (oauthChannelPo == null) {
                // 新增授权记录
                commonService.insertCustOauthChannel(preCustomerNo, systemId, mainSystemId, subSystemId);
                //恒生活授权后用户信息同步给恒易卡系统
                String remark = "恒生活系统授权同步用户信息";
                commonService.insertCustomerExtend(systemId, subSystemId, remark, preCustomerNo);
            } else {
                //授权记录为2 无效状态时，更新cust_extend与cust_oauth_channel相应记录
                if (oauthChannelPo.getStatus() == 2) {
                    log.info("【授权接口】注销后，再授权登录特殊场景>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>参数：{}", oauthChannelPo);
                    String remark = "注销后，再授权登录";
                    commonService.updateChannelById(oauthChannelPo.getId(), 1, remark);
                    commonService.updateCustExtendByAuth(preCustomerNo, systemId, subSystemId, 1);
                }
            }
            //查询cust_oauth_token表，如果存在记录则删除
//            commonService.deleteCustOauthToken(preCustomerNo, subSystemId);
            String loginCode = UUIDUtils.getUUID();
            CustOauthTokenPo po = commonService.getOauthCode(preCustomerNo, subSystemId);
            if (po != null) {
                //更新------一般调授权接口是新增，不会走到此步(注销后 授权登录可能走到此步)
                commonService.updateCustOauthToken(preCustomerNo, subSystemId, loginCode, null, CustomerConstants.UNREGISTER_STATUS, mainSystemId);
            } else {
                //token表新增授权记录
                commonService.insertCustOauthToken(preCustomerNo, systemId, subSystemId, loginCode, null, CustomerConstants.UNREGISTER_STATUS, mainSystemId);
                //更新授权流水表状态为已授权注册--3
                commonService.updateCustOauthLoginFlow(mainSystemId, subSystemId, code, preCustomerNo, 3);
            }
            map.put("code", loginCode);
            return map;
        } catch (CustomerException e) {
            log.error("【授权接口】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> getInfoByToken(BaseRequest<UnifyTokenInfoRo> bRequest) {
        log.info("【token获取用户信息接口】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            UnifyTokenInfoRo ro = bRequest.getBody();
            UnifyTokenInfoRo.checkBaseParam(ro);
            String accessToken = ro.getAccessToken();
            String customerNo = null;
            String subSystemId = bRequest.getSubSystemSign();
            String systemSign = bRequest.getSystemSign();
            Map<String, Object> map = new HashMap<>();
            //依据token查询信息是否存在
            CustOauthTokenVo vo = commonService.getOauthTokenInfo(accessToken, subSystemId);
            if (vo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "accessToken不存在!");
            } else {
                map.put("preCustomerNo", vo.getPreCustomerNo());
                map.put("phone", vo.getContactInfo());
                customerNo = vo.getCustomerNo();
            }
            CustOauthTokenPo oauthTokenPo = commonService.getOauthToken(accessToken, subSystemId);
            if (oauthTokenPo != null && StringUtils.isNotBlank(oauthTokenPo.getCustomerNo())) {
                customerNo = oauthTokenPo.getCustomerNo();
            }
            map.put("requestNo", ro.getRequestNo());
            map.put("customerNo", customerNo);
            map.put("systemSign", bRequest.getSystemSign());
            //最近登陆来源
            if (StringUtils.isNotBlank(oauthTokenPo.getCreditSystem())) {
                subSystemId = oauthTokenPo.getCreditSystem();
            }
            map.put("subSystemSign", subSystemId);
            CustomerExtendPo regiesterInfo = commonService.getRegisterSystem(oauthTokenPo.getPreCustomerNo(), systemSign);
            String registerSystem = null;
            if (regiesterInfo != null) {
                registerSystem = regiesterInfo.getSubSystemSign();
            }
            map.put("registerSystem", registerSystem);
            return map;
        } catch (CustomerException e) {
            log.error("【token获取用户信息接口】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    private void checkUnifyParam(String systemSign, String subSystemSign) {
        try {
            if (StringUtils.isBlank(systemSign)) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "系统标识不能为空!");
            }
            if (StringUtils.isBlank(subSystemSign)) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "子系统标识不能为空!");
            }
            if (CustomerConstants.HSH.equals(systemSign)) {
                systemSign = CustomerConstants.YZT;
            }
            SystemInfoPo po = commonService.getSystemInfo(systemSign, subSystemSign);
            if (po == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "系统不存在!");
            }
        } catch (DataAccessException e) {
            log.error("查询系统表报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    public String isToSendSmsCode(String mobile, String subSystemSign, String ip) {
        String result = "0";
        //防止同一ip刷，10分钟不超过5次
        if (propertiesConfig.isVerifyIp()) {
            List<UnifySmsCodeFlowPo> ipPos = unifySmsMapper.getUnifySmsCodeFlowRecently(null, null, ip);
            if (ipPos == null || ipPos.size() < 6) {
                //正常状态
            } else {
                //同一ip超过5次
                return "1";
            }
        }
        //防止同一手机号刷
        //优先判断有没有超额 超额则直接返回锁定时间
        List<String> date = getCurrentTimeAndTomorrow();
        String today = date.get(0);
        String tomorrow = date.get(1);
        List<UnifySmsCodeFlowPo> pos = unifySmsMapper.getUnifySmsCodeToday(subSystemSign, mobile, today, tomorrow);
        if (pos == null || pos.size() < 10) {
            //正常状态，查询最近一条记录是否有解锁时间
            UnifySmsCodeFlowPo po = unifySmsMapper.getUnifySmsCode(subSystemSign, mobile);
            if (po != null && po.getUnlockTime() != null) {
                //处于锁定 查看是否到锁定时间
                Timestamp now = new Timestamp(System.currentTimeMillis());
                long residueTime = now.getTime() - po.getUnlockTime().getTime();
                if (residueTime > 0) {
                    //超过锁定时间
                } else {
                    //还处于锁定状态
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(po.getUnlockTime());
                }
            }
        } else {
            //超额
            Timestamp timestamp = pos.get(0).getCreateTime();
            //加一天
            long time = timestamp.getTime() + (long) 1000 * 3600 * 24;
            Timestamp timestamp2 = new Timestamp(time);
            String unlockTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp2);
            //插入锁定截止时间
            commonService.updateCustUnifySmsFlow(timestamp2, pos.get(0).getId());
            return unlockTime;
        }
        //判断十分钟内超过两次
        List<UnifySmsCodeFlowPo> phonePos = unifySmsMapper.getUnifySmsCodeFlowRecently(subSystemSign, mobile, null);
        if (phonePos == null || phonePos.size() < 2) {
            //正常状态
        } else {
            //同一手机号十分钟内超过2次
            return "2";
        }
        return result;
    }

    public List<String> getCurrentTimeAndTomorrow() {
        List<String> date = new ArrayList<>();
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        Calendar c = Calendar.getInstance();
//        String today = sdf.format(c.getTime());
        String today = LocalDateUtils.getLocalDateStr();
        String tomorrow = LocalDateUtils.format(LocalDateUtils.plus(LocalDateTime.now(), 1, ChronoUnit.DAYS), LocalDateUtils.DATE_PATTERN);
//        c.add(Calendar.DATE, 1);//-1.昨天时间 0.当前时间 1.明天时间 *以此类推
//        String tomorrow = sdf.format(c.getTime());
        today = today + " 00:00:00";
        tomorrow = tomorrow + " 00:00:00";
        date.add(today);
        date.add(tomorrow);
        return date;
    }

    public String sendSmsLimit(String mobile, String subSystemSign, String type) {
        //优先判断有没有超额 超额则直接返回锁定时间
        List<String> date = getCurrentTimeAndTomorrow();
        String today = date.get(0);
        String tomorrow = date.get(1);
        List<UnifySmsPwdFlowPo> pos = pwdFlowMapper.getSmsFLowToday(subSystemSign, mobile, today, tomorrow, type);
        if (pos == null || pos.size() < 10) {
            //正常状态，查询最近一条记录是否有解锁时间
            UnifySmsPwdFlowPo po = pwdFlowMapper.getSmsFLow(subSystemSign, mobile, type);
            if (po != null && po.getUnlockTime() != null) {
                //处于锁定 查看是否到锁定时间
                Timestamp now = new Timestamp(System.currentTimeMillis());
                long residueTime = now.getTime() - po.getUnlockTime().getTime();
                if (residueTime > 0) {
                    //超过锁定时间
                } else {
                    //还处于锁定状态
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(po.getUnlockTime());
                }
            }
        } else {
            //超额
            Timestamp timestamp = pos.get(0).getCreateTime();
            //加一天
            long time = timestamp.getTime() + (long) 1000 * 3600 * 24;
            Timestamp timestamp2 = new Timestamp(time);
            String unlockTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp2);
            //插入锁定截止时间
            commonService.updateCustSmsPwdFlow(timestamp2, pos.get(0).getId());
            return unlockTime;
        }
        return "0";
    }

    @Override
    public Map<String, Object> getRandomCodeBase64() {
        try {
            Map<String, Object> map = new HashMap<>();
            ValidateCodeUtils validateCode = new ValidateCodeUtils();
            Map<String, Object> validateMap = validateCode.getRandomCodeBase64();
            // 返回base64
            String graphicUrl = "data:image/png;base64," + validateMap.get("base64String");
            String graphicCode = validateMap.get("randomString").toString();
            String graphicKey = UUIDUtils.getUUID();
            redisService.setObj(graphicKey, graphicCode, 60 * 5);
            map.put("graphicUrl", graphicUrl);
            map.put("graphicKey", graphicKey);
            log.info("redis存储key为:" + graphicKey);
            return map;
        } catch (Exception e) {
            log.error("获取图形验证码报错:" + e);
            throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "获取图形验证码报错");
        }
    }

    @Override
    public Map<String, Object> graphicVerify(UnifygraphicRo ro) {
        log.info("【图形验证码校验】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", ro);
        try {
            UnifygraphicRo.checkBaseParam(ro);
            String graphicKey = ro.getGraphicKey();
            String graphicCode = ro.getGraphicCode();
            String systemSign = ro.getSysytemSign();
            String subSystemSign = ro.getSubSystemSign();
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(systemSign, subSystemSign);
            boolean checked = false;
            Object redisCode = redisService.getObj(graphicKey);
            if (redisCode != null) {
                // 比较code值
                String redisCodeStr = redisCode.toString();
                if (graphicCode.equalsIgnoreCase(redisCodeStr)) {
                    //防刷规则处理解封
                    checked = true;
                }
            }
            map.put("checked", checked);
            return map;
        } catch (CustomerException e) {
            log.error("【图形验证码校验】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> refreshGraphic(UnifyRefreshGraphicRo ro) {
        log.info("【图形验证码刷新接口】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", ro);
        try {
            Map<String, Object> map = new HashMap<>();
            //获取图形验证码
            Map<String, Object> graphicMap = getRandomCodeBase64();
            map.put("graphicUrl", graphicMap.get("graphicUrl"));
            map.put("graphicKey", graphicMap.get("graphicKey"));
            return map;
        } catch (CustomerException e) {
            log.error("【图形验证码刷新接口】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> queryCustInfo(BaseRequest<CustomerUnifyQueryInfoRo> request) {
        log.info("【支付中台-客户信息查询】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        CustomerUnifyQueryInfoRo ro = request.getBody();
        String customerNo = ro.getCustomerNo();
        String preCustomerNo = ro.getPreCustomerNo();
        String targetSystemSign = ro.getTargetSystemSign();
        String targetSubSystemSign = ro.getTargetSubSystemSign();
        Map<String, Object> map = new HashMap<>();
        try {
            //参数校验
            CustomerUnifyQueryInfoRo.checkBaseParam(ro);
            checkUnifyParam(targetSystemSign, targetSubSystemSign);
            //检查入参用户客户是否存在
            List<CustOauthTokenVo> dataVos = customerUnifyMapper.getCustomerInfo(preCustomerNo, null, targetSubSystemSign);
            if (dataVos.size() == 0) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "用户信息错误");
            }
            String phone = dataVos.get(0).getContactInfo();
            List<String> customerNos = new ArrayList();
            for (CustOauthTokenVo dataVo : dataVos) {
                customerNos.add(dataVo.getCustomerNo());
            }
            if (StringUtils.isNotBlank(customerNo) && (!customerNos.contains(customerNo))) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "客户信息错误");
            }
            if (StringUtils.isNotBlank(dataVos.get(0).getCustomerNo())) {
                if (StringUtils.isBlank(customerNo)) {
                    customerNo = dataVos.get(0).getCustomerNo();
                }
                //查询三要素
                CustomerIdInfoPo idInfoPo = commonService.getCustomerIdInfo(customerNo);
                if (idInfoPo == null) {
                    CompanyIdInfoPo companyInfoPo = commonService.getCompanyIdInfo(customerNo);
                    if (companyInfoPo == null) {
                        throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "客户信息错误");
                    }
                    map.put("userType", 2);
                    map.put("customerType", companyInfoPo.getCustomerType());
                    map.put("customerName", companyInfoPo.getCustomerName());
                    map.put("customerPhoneNo", companyInfoPo.getCustomerPhoneNo());
                    map.put("customerCertNo", companyInfoPo.getCustomerCertNo());
                    map.put("corprateName", companyInfoPo.getLegalName());
                    map.put("corprateCertType", companyInfoPo.getIdCardType());
                    map.put("corprateCertNo", companyInfoPo.getIdCardNo());
                    map.put("corprateCertExpiry", companyInfoPo.getCorprateCertExpiry());
                    map.put("corprateCertExpiryend", companyInfoPo.getCorprateCertExpiryend());
                    map.put("corprateMobile", companyInfoPo.getCorprateMobile());
                    map.put("operatorName", companyInfoPo.getOperatorName());
                    map.put("operatorCertType", companyInfoPo.getOperatorCertType());
                    map.put("operatorCertNo", companyInfoPo.getOperatorCertNo());
                    map.put("operatorCertExpiry", companyInfoPo.getOperatorCertExpiry());
                    map.put("operatorCertExpiryend", companyInfoPo.getCorprateCertExpiryend());
                    map.put("operatorMobile", companyInfoPo.getOperatorMobile());
                    map.put("customerCertPid", companyInfoPo.getCustomerCertPid());
                    map.put("corpratePic1", companyInfoPo.getCorpratePic1());
                    map.put("corpratePic2", companyInfoPo.getCorpratePic2());
                    return map;
                }
                String name = idInfoPo.getCustomerName();
                String idCardNo = idInfoPo.getIdCardNo();
                String idCardType = idInfoPo.getIdCardType();
                map.put("name", name);
                map.put("idCardNo", idCardNo);
                map.put("idCardType", idCardType);
                map.put("userType", 1);
                map.put("phone", phone);
            }
            return map;
        } catch (CustomerException e) {
            log.error("【支付中台-客户信息查询】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> getBusinessUser(BaseRequest<CustomerInfoRo> bRequest) {
        log.info("【生成商户登录账号】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", bRequest);
        try {
            CustomerInfoRo.checkBaseParam(bRequest.getBody());
            String phone = bRequest.getBody().getPhone();
            String requestNo = bRequest.getBody().getRequestNo();
            String contactType = CustomerConstants.CONTACT_TYPE_MOBILE;
            String systemSign = bRequest.getSystemSign();
            String subSystemSign = bRequest.getSubSystemSign();
            BaseRequest<PreCustomerRo> preRequest = new BaseRequest<>();
            PreCustomerRo unifyRegisterRo = new PreCustomerRo();
            unifyRegisterRo.setRequestNo(requestNo);
            unifyRegisterRo.setContactInfo(phone);
            unifyRegisterRo.setContactType(CustomerConstants.CONTACT_TYPE_MOBILE);
            preRequest.setSystemSign(systemSign);
            preRequest.setSubSystemSign(subSystemSign);
            preRequest.setBody(unifyRegisterRo);
            Map<String, String> map = new HashMap<>();
            map.put("requestNo", requestNo);
            //注册
            PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(contactType, phone);
            String registPreCustomerNo = null;
            String customerNo = null;
            if (preCustomerInfoPo != null) {
                String preCustomerNo = preCustomerInfoPo.getPreCustomerNo();
                registPreCustomerNo = preCustomerInfoPo.getPreCustomerNo();
                List<CustomerExtendPo> registerList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 1);
                List<CustomerExtendPo> register4DeleteList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 6);
                if (registerList.size() > 0) {

                } else if (registerList.size() == 0 && register4DeleteList.size() > 0) {
                    //基于id更新extend表状态
                    commonService.updateCustExtendById(register4DeleteList.get(0).getId(), 1);
                    registPreCustomerNo = preCustomerNo;
                } else {
                    //统一注册用户创建用户号
                    Map<String, String> registerInfo = basePreCustomerService.createUnifyPreCustomerNo(preRequest);
                    registPreCustomerNo = registerInfo.get("preCustomerNo");
                }
            } else {
                //统一注册用户创建用户号
                Map<String, String> registerInfo = basePreCustomerService.createUnifyPreCustomerNo(preRequest);
                registPreCustomerNo = registerInfo.get("preCustomerNo");
            }
            //实名
            bRequest.getBody().setPreCustomerNo(registPreCustomerNo);
            Map<String, String> resMap = baseCustomerService.createCustomerNo(bRequest);
            //插入code，暂时不需要，有需要再放开
            String code = UUIDUtils.getUUID();
            CustOauthTokenPo po = commonService.getOauthCode(registPreCustomerNo, subSystemSign);
            if (po != null) {
                //更新
                commonService.updateCustOauthToken(registPreCustomerNo, subSystemSign, code, null, CustomerConstants.REGISTER_STATUS, "");
            } else {
                //新增
                commonService.insertCustOauthToken(registPreCustomerNo, systemSign, subSystemSign, code, 1, CustomerConstants.REGISTER_STATUS, "");
            }
            //发送短信
            Map<String, String> sendSmsRuleMap = DictionaryFactory.Dict.SEND_SMS_RULE.getDictMap();
            String sendRule = sendSmsRuleMap.get(subSystemSign);
            //发送短信 send发 unsend不发
            if (StringUtils.isNotBlank(sendRule) && sendRule.equals("send")) {
                commonService.sendSms(phone, phone, systemSign, subSystemSign, CustomerConstants.SMS_TEMPLATE_TZ);
            }
            customerNo = resMap.get("customerNo");
            map.put("preCustomerNo", registPreCustomerNo);
            map.put("customerNo", customerNo);
            return map;
        } catch (CustomerException e) {
            log.error("【生成商户登录账号】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> getFormalCode(UnifyFormalCodeRo ro) {
        log.info("【依据临时code换取正式code】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", ro);
        try {
            UnifyFormalCodeRo.checkBaseParam(ro);
            String requestNo = ro.getRequestNo();
            String tempCode = ro.getTempCode();
            String preCustomerNo = ro.getPreCustomerNo();
            String customerNo = ro.getCustomerNo();
            //查询code信息是否存在
            CustOauthTokenPo oauthTokenPo = commonService.getOauthCode(tempCode);
            if (oauthTokenPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "tempCode信息不存在!");
            }
            if (!preCustomerNo.equals(oauthTokenPo.getPreCustomerNo())) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "用户信息不存在!");
            }
            String loginCode = UUIDUtils.getUUID();
            commonService.updateCode(oauthTokenPo.getId(), customerNo, loginCode);
            Map<String, Object> map = new HashMap<>();
            map.put("code", loginCode);
            map.put("requestNo", requestNo);
            return map;
        } catch (CustomerException e) {
            log.error("【依据临时code换取正式code】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> verifyRegister(BaseRequest<CustomerUnifyVerifyRo> bRequest) {
        log.info("【验证是否注册】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            CustomerUnifyVerifyRo ro = bRequest.getBody();
            CustomerUnifyVerifyRo.checkBaseParam(ro);
            String requestNo = ro.getRequestNo();
            String systemSign = bRequest.getSystemSign();
            String subSystemSign = bRequest.getSubSystemSign();
            checkUnifyParam(systemSign, subSystemSign);
            String status = "1";
            String domainName = null;
            Map<String, String> loginRuleDictMap = DictionaryFactory.Dict.UNIFY_DOMAIN_NAME.getDictMap();
            if (loginRuleDictMap != null && loginRuleDictMap.size() > 0) {
                domainName = loginRuleDictMap.get(subSystemSign);
            }
            List<PreCustomerInfoPo> registerList = customerExtendMapper.getRegisterPreCustomerInfo(ro.getPhone(), subSystemSign, 1);
            //status 0-已注册；1-未注册
            if (registerList != null && registerList.size() > 0) {
                status = "0";
            }
            Map<String, Object> map = new HashMap<>();
            map.put("requestNo", requestNo);
            map.put("status", status);
            map.put("domainName", domainName);
            return map;
        } catch (CustomerException e) {
            log.error("【验证是否注册】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> verifyCode(BaseRequest<UnifyCodeRo> bRequest) {
        log.info("【校验code是否失效】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            UnifyCodeRo ro = bRequest.getBody();
            UnifyCodeRo.checkBaseParam(ro);
            String code = ro.getCode();
            String requestNo = ro.getRequestNo();
            String subSystemSign = bRequest.getSubSystemSign();
            String systemSign = bRequest.getSystemSign();
            Map<String, Object> map = new HashMap<>();
            String status;
            checkUnifyParam(systemSign, subSystemSign);
            //查询code信息是否存在
            CustOauthTokenPo oauthTokenPo = commonService.getOauthCodeInfo(code, subSystemSign);
            // code 0-有效；1-无效
            if (oauthTokenPo != null) {
                status = "0";
                PreCustomerInfoPo po = commonService.getExistPreCustomer(oauthTokenPo.getPreCustomerNo());
                String phone = po.getContactInfo();
                map.put("phone", phone);
            } else {
                status = "1";
            }
            map.put("status", status);
            map.put("requestNo", requestNo);
            return map;
        } catch (CustomerException e) {
            log.error("【校验code是否失效】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> modifyBusinessInfo(BaseRequest<UnifyModifyBusinessRo> request) {
        log.info("【修改商户客户信息】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        UnifyModifyBusinessRo ro = request.getBody();
        String customerNo = ro.getCustomerNo();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        String requestNo = ro.getRequestNo();
        try {
            //参数校验
            UnifyModifyBusinessRo.checkBaseParam(ro);
            commonService.checkRepeatRequestNo(requestNo, TableEnum.COMPANY_MODIFY_FOLW);
            //检查入参用户客户是否存在
            CustomerManageInfoPo customerManageInfoPo = commonService.getCustomerManageInfo(customerNo, subSystemSign);
            if (customerManageInfoPo == null) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "当前系统客户号不存在");
            }
            CompanyIdInfoPo tmpPo = commonService.getCompanyIdInfo(customerNo);
            if (tmpPo == null) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "当前系统客户号不存在");
            }
            //修改前记录
            String modifyMsg = tmpPo.toString();
            CompanyIdInfoPo po = new CompanyIdInfoPo();
            po.setId(tmpPo.getId());
            if (StringUtils.isNotBlank(ro.getIdCardType())) {
                po.setIdCardType(ro.getIdCardType());
            }
            if (StringUtils.isNotBlank(ro.getIdCardNo())) {
                po.setIdCardNo(ro.getIdCardNo());
            }
            if (StringUtils.isNotBlank(ro.getLegalName())) {
                po.setLegalName(ro.getLegalName());
            }
            if (StringUtils.isNotBlank(ro.getCustomerPhoneNo())) {
                po.setCustomerPhoneNo(ro.getCustomerPhoneNo());
            }
            if (StringUtils.isNotBlank(ro.getCustomerCertNo())) {
                po.setCustomerCertNo(ro.getCustomerCertNo());
            }
            if (StringUtils.isNotBlank(ro.getCorprateCertExpiry())) {
                po.setCorprateCertExpiry(ro.getCorprateCertExpiry());
            }
            if (StringUtils.isNotBlank(ro.getCorprateCertExpiryend())) {
                po.setCorprateCertExpiryend(ro.getCorprateCertExpiryend());
            }
            if (StringUtils.isNotBlank(ro.getCorprateMobile())) {
                po.setCorprateMobile(ro.getCorprateMobile());
            }
            if (StringUtils.isNotBlank(ro.getOperatorName())) {
                po.setOperatorName(ro.getOperatorName());
            }
            if (StringUtils.isNotBlank(ro.getOperatorCertType())) {
                po.setOperatorCertType(ro.getOperatorCertType());
            }
            if (StringUtils.isNotBlank(ro.getOperatorCertNo())) {
                po.setOperatorCertNo(ro.getOperatorCertNo());
            }
            if (StringUtils.isNotBlank(ro.getOperatorCertExpiry())) {
                po.setOperatorCertExpiry(ro.getOperatorCertExpiry());
            }
            if (StringUtils.isNotBlank(ro.getOperatorCertExpiryend())) {
                po.setOperatorCertExpiryend(ro.getOperatorCertExpiryend());
            }
            if (StringUtils.isNotBlank(ro.getOperatorMobile())) {
                po.setOperatorMobile(ro.getOperatorMobile());
            }
            if (StringUtils.isNotBlank(ro.getCustomerCertPid())) {
                po.setCustomerCertPid(ro.getCustomerCertPid());
            }
            if (StringUtils.isNotBlank(ro.getCustomerType())) {
                po.setCustomerType(ro.getCustomerType());
            }
            if (StringUtils.isNotBlank(ro.getCorpratePic1())) {
                po.setCorpratePic1(ro.getCorpratePic1());
            }
            if (StringUtils.isNotBlank(ro.getCorpratePic2())) {
                po.setCorpratePic2(ro.getCorpratePic2());
            }
            companyIdInfoMapper.updateByPrimaryKeySelective(po);
            //记录修改客户信息流水
            commonService.insertCompanyModifyFlow(ro, systemSign, subSystemSign, modifyMsg);
            Map<String, Object> map = new HashMap<>();
            map.put("requestNo", ro.getRequestNo());
            return map;
        } catch (CustomerException e) {
            log.error("【修改商户客户信息】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }

    }

    @Override
    public Map<String, Object> queryBusinessModify(BaseRequest<CustomerUnifyQueryInfoRo> request) {
        log.info("【查询商户修改信息记录】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        CustomerUnifyQueryInfoRo ro = request.getBody();
        try {
            //参数校验
            CustomerUnifyQueryInfoRo.checkBaseParam(ro);
            CompanyModifyFlowPo po = new CompanyModifyFlowPo();
            po.setPreCustomerNo(ro.getPreCustomerNo());
            po.setRequestNo(ro.getRequestNo());
            po.setCustomerNo(ro.getCustomerNo());
            po.setSubSystemSign(ro.getTargetSubSystemSign());
            po.setSystemSign(ro.getTargetSystemSign());
            List<CompanyModifyFlowPo> pos = companyModifyFlowMapper.select(po);
            Map<String, Object> map = new HashMap<>();
            map.put("requestNo", ro.getRequestNo());
            if (pos != null && pos.size() > 0) {
                CompanyModifyFlowPo data = pos.get(0);
//                map = JSON.parseObject(JSON.toJSONString(data), Map.class);
                if (StringUtils.isNotBlank(data.getCustomerPhoneNo())) {
                    map.put("customerPhoneNo", data.getCustomerPhoneNo());
                }
                if (StringUtils.isNotBlank(data.getCustomerCertNo())) {
                    map.put("customerCertNo", data.getCustomerCertNo());
                }
                if (StringUtils.isNotBlank(data.getCorprateCertExpiry())) {
                    map.put("corprateCertExpiry", data.getCorprateCertExpiry());
                }
                if (StringUtils.isNotBlank(data.getCorprateCertExpiryend())) {
                    map.put("corprateCertExpiryend", data.getCorprateCertExpiryend());
                }
                if (StringUtils.isNotBlank(data.getCorprateMobile())) {
                    map.put("corprateMobile", data.getCorprateMobile());
                }
                if (StringUtils.isNotBlank(data.getOperatorName())) {
                    map.put("operatorName", data.getOperatorName());
                }
                if (StringUtils.isNotBlank(data.getOperatorCertType())) {
                    map.put("operatorCertType", data.getOperatorCertType());
                }
                if (StringUtils.isNotBlank(data.getOperatorCertNo())) {
                    map.put("operatorCertNo", data.getOperatorCertNo());
                }
                if (StringUtils.isNotBlank(data.getOperatorCertExpiry())) {
                    map.put("operatorCertExpiry", data.getOperatorCertExpiry());
                }
                if (StringUtils.isNotBlank(data.getOperatorCertExpiryend())) {
                    map.put("operatorCertExpiryend", data.getOperatorCertExpiryend());
                }
                if (StringUtils.isNotBlank(data.getOperatorMobile())) {
                    map.put("operatorMobile", data.getOperatorMobile());
                }
                if (StringUtils.isNotBlank(data.getCustomerCertPid())) {
                    map.put("customerCertPid", data.getCustomerCertPid());
                }
                if (StringUtils.isNotBlank(data.getCustomerType())) {
                    map.put("customerType", data.getCustomerType());
                }
                if (StringUtils.isNotBlank(data.getCorpratePic1())) {
                    map.put("corpratePic1", data.getCorpratePic1());
                }
                if (StringUtils.isNotBlank(data.getCorpratePic2())) {
                    map.put("corpratePic2", data.getCorpratePic2());
                }
                if (StringUtils.isNotBlank(data.getLegalName())) {
                    map.put("corprateName", data.getLegalName());
                }
                if (StringUtils.isNotBlank(data.getIdCardType())) {
                    map.put("corprateCertType", data.getIdCardType());
                }
                if (StringUtils.isNotBlank(data.getIdCardNo())) {
                    map.put("corprateCertNo", data.getIdCardNo());
                }
            } else {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "未查询到相关信息");
            }
            return map;
        } catch (CustomerException e) {
            log.error("【查询修改商户客户信息】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }


//    @Override
//    @Transactional(rollbackFor = Exception.class)
//    public Map<String, Object> mSaRegister(BaseRequest<CustomerUnifySubRegisterRo> bRequest) {
//        log.info("【恒小花商户子账号注册】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:", bRequest);
//        CustomerUnifySubRegisterRo ro = bRequest.getBody();
//        String phone = ro.getPhone();
//        String contactType = CustomerConstants.CONTACT_TYPE_MOBILE;
//        String systemSign = bRequest.getSystemSign();
//        String subSystemSign = bRequest.getSubSystemSign();
//        String customerNo = ro.getCustomerNo();
//        String requestNo = ro.getRequestNo();
//        try {
//            CustomerUnifySubRegisterRo.checkBaseParam(ro);
//            CustomerManageInfoPo manageInfoPo = commonService.getCustomerManageInfo(customerNo, subSystemSign);
//            if (manageInfoPo == null) {
//                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "客户不存在，请核实重新发起注册");
//            }
//            Map<String, Object> map = new HashMap<>();
//            BaseRequest<CustomerUnifyRegisterRo> preRequest = new BaseRequest<>();
//            CustomerUnifyRegisterRo unifyRegisterRo = new CustomerUnifyRegisterRo();
//            unifyRegisterRo.setRequestNo(bRequest.getBody().getRequestNo());
//            unifyRegisterRo.setPhone(phone);
//            preRequest.setSystemSign(systemSign);
//            preRequest.setSubSystemSign(subSystemSign);
//            preRequest.setBody(unifyRegisterRo);
//            //注册
//            PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(contactType, phone);
//            //新注册用户号
//            String registPreCustomerNo = null;
//            if (preCustomerInfoPo != null) {
//                String preCustomerNo = preCustomerInfoPo.getPreCustomerNo();
//                registPreCustomerNo = preCustomerNo;
//                List<CustomerExtendPo> registerList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 1);
//                List<CustomerExtendPo> register4DeleteList = customerExtendMapper.getRegisterInfoBySubSystemAndStatus(preCustomerNo, subSystemSign, 6);
//                if (registerList.size() > 0) {
//                    throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "当前手机号已注册");
//                } else if (registerList.size() == 0 && register4DeleteList.size() > 0) {
//
//                    //基于id更新extend表状态
//                    commonService.updateCustExtendById(register4DeleteList.get(0).getId(), 1);
//                    registPreCustomerNo = preCustomerNo;
//                } else {
//                    Map<String, Object> registerInfo = createPre(preRequest);
//                    registPreCustomerNo = registerInfo.get("preCustomerNo").toString();
//                }
//            } else {
//                Map<String, Object> registerInfo = createPre(preRequest);
//                registPreCustomerNo = registerInfo.get("preCustomerNo").toString();
//            }
//            //todo 新用户号关联客户号
//            baseCustomerService.updateCustomerExtend(systemSign, subSystemSign, customerNo, registPreCustomerNo);
//            //插入code，暂时不需要，有需要再放开
//            String code = UUIDUtils.getUUID();
//            CustOauthTokenPo po = commonService.getOauthCode(registPreCustomerNo, subSystemSign);
//            if (po != null) {
//                //更新
//                commonService.updateCustOauthToken(registPreCustomerNo, subSystemSign, code, null, CustomerConstants.REGISTER_STATUS, "");
//            } else {
//                //新增
//                commonService.insertCustOauthToken(registPreCustomerNo, systemSign, subSystemSign, code, 1, CustomerConstants.REGISTER_STATUS, "");
//            }
//            map.put("preCustomerNo", registPreCustomerNo);
//            map.put("customerNo", customerNo);
//            map.put("requestNo", requestNo);
//            return map;
//        } catch (CustomerException e) {
//            log.error("【恒小花商户子账号注册】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
//            throw new CustomerException(e.getCode(), e.getMsg());
//        }
//
//    }

    @Override
    public Map<String, Object> getInvitationInfo(BaseRequest<CustomerInvitationRo> request) {
        log.info("【用户获取邀请码】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", request);
        try {
            CustomerInvitationRo ro = request.getBody();
            String preCustomerNo = ro.getPreCustomerNo();
            String systemSign = request.getSystemSign();
            String subSystemSign = request.getSubSystemSign();
            String requestNo = ro.getRequestNo();
            CustomerInvitationRo.checkBaseParam(ro);
            checkUnifyParam(systemSign, subSystemSign);
            Map<String, Object> map = new HashMap<>();
            //判断用户号是否存在
            CustomerExtendPo extendPo = commonService.getExistPreCustomerExtend(preCustomerNo, systemSign, subSystemSign);
            if (extendPo == null) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "用户号不存在");
            }
            CustInvitationCodePo invitationCodePo = commonService.getInvitationCode(preCustomerNo, systemSign, subSystemSign);
            if (invitationCodePo == null) {
                PreCustomerInfoPo preCustomerInfoPo = commonService.getExistPreCustomer(preCustomerNo);
                String phone = preCustomerInfoPo.getContactInfo();
                //生成随机邀请码
                String invitationCode = RC4.getInvitationCode();
                commonService.insertInvitationCode(preCustomerNo, phone, invitationCode, systemSign, subSystemSign);
                map.put("invitationCode", invitationCode);
            } else {
                map.put("invitationCode", invitationCodePo.getInvitationCode());
            }
            //获取邀请人邀请码
            CustInvitationRelationPo invitationRelationPo = commonService.getInvitationRelation(preCustomerNo, systemSign, subSystemSign);
            if (invitationRelationPo != null) {
                map.put("inviterCode", invitationRelationPo.getInvitationCode());
            }
            map.put("requestNo", requestNo);
            return map;
        } catch (CustomerException e) {
            log.error("【用户获取邀请码】接口异常>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", e.getMsg());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fixCustNo(BaseRequest<CustomerUnifyFixRo> bRequest) {
        log.info("【客户信息修复】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        CustomerUnifyFixRo ro = bRequest.getBody();
        String preCustomerNo = ro.getPreCustomerNo();
        String customerNo = ro.getCustomerNo();
        String fixCustomerNo = ro.getNewCustomerNo();
        String systemSign = bRequest.getSystemSign();
        String subSystemSign = bRequest.getSubSystemSign();
        Integer status = CustomerConstants.STATUS_SUCCESS;
        String errorMsg = null;
        try {
            CustomerUnifyFixRo.checkBaseParam(ro);
            //查询用户号与客户号是否存在
            CustomerExtendPo extendPo = commonService.getExistCustomerExtend(preCustomerNo, customerNo, systemSign, subSystemSign);
            if (extendPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "当前客户信息不存在!");
            }
            CustomerIdInfoPo infoPo = commonService.getExistCustomer(customerNo, systemSign, subSystemSign);
            CustomerIdInfoPo newInfoPo = commonService.getExistCustomer(fixCustomerNo, systemSign, subSystemSign);
            if (infoPo != null && newInfoPo != null && infoPo.getIdCardNo().equals(newInfoPo.getIdCardNo())
                    && infoPo.getCustomerName().equals(newInfoPo.getCustomerName())) {
                //满足修复条件，1:cust_extend修复客户号；2清理失效客户号信息
                log.info("客户信息修复中>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                updateCustomerExtend(systemSign, subSystemSign, customerNo, fixCustomerNo);
                commonService.deleteCustIdInfoById(infoPo.getId());
                commonService.deleteCustManageInfo(customerNo, subSystemSign);
            } else {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "当前客户信息不能修复!");
            }
        } catch (CustomerException e) {
            status = CustomerConstants.STATUS_FAIL;
            errorMsg = e.getMsg();
            log.error("【客户信息修复】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        } finally {
            commonService.insertCustUnifyUpdateFlow(bRequest.toString(), systemSign, subSystemSign, ro.getRequestNo(), status, errorMsg);
        }
    }

    @Override
    public Map<String, Object> sendSms(BaseRequest<UnifySmsPwdRo> request) {
        log.info("【统一登录-发送短信】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参:{}", request);
        UnifySmsPwdRo ro = request.getBody();
        String requestNo = ro.getRequestNo();
        String mobile = ro.getPhone();
        String ip = ro.getIp();
        String smsType = ro.getSmsType();
        String systemSign = request.getSystemSign();
        String subSystemSign = request.getSubSystemSign();
        Integer content;
        Integer status = CustomerConstants.STATUS_SUCCESS;
        String errorMsg = null;
        String smsCode = null;
        String type = CustomerConstants.SMS_TEMPLATE_PWD_YZM;
        try {
            UnifySmsPwdRo.checkBaseParam(ro);
            checkUnifyParam(systemSign, subSystemSign);
            Map<String, Object> map = new HashMap<>(2);
            map.put("requestNo", requestNo);
            //todo 手机号139不发三方挡板
//            if (mobile.startsWith("139")) {
//                return map;
//            }
            //是否超数 0-正常状态
            String time = sendSmsLimit(mobile, subSystemSign, smsType);
            if (!time.equals("0")) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "获取短信验证码过于频繁，请24小时后重试");
            }
            //生成验证码
            content = (int) ((Math.random() * 9 + 1) * 100000);
            smsCode = content.toString();
            //发送短信验证码
            commonService.sendSms(mobile, smsCode, systemSign, subSystemSign, type);
            return map;
        } catch (CustomerException e) {
            status = CustomerConstants.STATUS_FAIL;
            errorMsg = e.getMsg();
            log.error("【统一登录-发送短信】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        } finally {
            commonService.insertCustSmsPwdFlow(mobile, systemSign, subSystemSign, requestNo, status, errorMsg, smsCode, ip, StringUtils.isBlank(smsType) ? null : Integer.parseInt(smsType));
        }
    }

    @Override
    public void verifySms(BaseRequest<VerifySmsCodeRo> bRequest) {
        log.info("【校验短信验证码】接口开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            VerifySmsCodeRo ro = bRequest.getBody();
            VerifySmsCodeRo.checkBaseParam(ro);
            String phone = ro.getPhone();
            String smsCode = ro.getSmsCode();
            String smsType = ro.getSmsType();
            String subSystemSign = bRequest.getSubSystemSign();
            String systemSign = bRequest.getSystemSign();
            checkUnifyParam(systemSign, subSystemSign);
            //todo 添加验证码666666不校验挡板
            boolean isCorrect = false;
            if (smsCode.equals("888888")) {
                //当为配置手机号段时，发送固定短信验证码888888
                Map<String, String> fixedCodeDictMap = DictionaryFactory.Dict.UNIFY_FIXED_CODE.getDictMap();
                String fixedCodeRule = fixedCodeDictMap.get("HSH");
                if (StringUtils.isNotBlank(fixedCodeRule)) {
                    String[] rule = fixedCodeRule.split("/");
                    String fixedPhone = rule[1];
                    if (fixedPhone.contains(phone)) {
                        isCorrect = true;
                    } else {
                        isCorrect = verifySmsPwd(subSystemSign, phone, smsCode, smsType);
                    }
                }
            } else {
                isCorrect = verifySmsPwd(subSystemSign, phone, smsCode, smsType);
            }
            if (!isCorrect) {
                throw new CustomerException(CustomerCodes.BIZ_VALIDATE_ERROR, "验证码无效，请重新输入");
            }
        } catch (CustomerException e) {
            log.error("【校验短信验证码】接口异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    private boolean verifySmsPwd(String subSystemSign, String phone, String smsCode, String smsType) {
        UnifySmsPwdFlowPo po = pwdFlowMapper.getSmsCodeRecently(subSystemSign, phone, smsCode, smsType);
        return po != null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> auth(BaseRequest<UnifyAuthRo> bRequest) {
        log.info("【统一授权接口】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            UnifyAuthRo ro = bRequest.getBody();
            UnifyAuthRo.checkBaseParam(ro);
            //本系统标识
            String systemSign = bRequest.getSystemSign();
            String subSystemSign = bRequest.getSubSystemSign();
            String requestNo = ro.getRequestNo();
            String preCustomerNo = ro.getPreCustomerNo();
            //被授权系统标识
            String authSystem = ro.getAuthSystem();
            String authSubSystem = ro.getAuthSubSystem();
            String systemId = CustomerConstants.YZT;
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(authSystem, authSubSystem);
            //判断前端是否需要验签
//            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
//            String checkRule = checkRuleDictMap.get(mainSystemId);
//            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
//                commonService.verifySignature(mainSystemId, ro.getTimestamp(), code, ro.getVerifyCode());
//            }
            //查询preCustomerNo是否存在
            CustomerExtendPo extendPo = commonService.getExistPreCustomerExtend(preCustomerNo,systemSign,subSystemSign);
            if (extendPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "preCustomerNo用户号不存在!");
            }
            //cust_oauth_channel渠道表新增授权记录
            CustOauthChannelPo oauthChannelPo = commonService.getOauthChannel(preCustomerNo, subSystemSign, authSubSystem);
            if (oauthChannelPo == null) {
                // 新增授权记录
                commonService.insertCustOauthChannel(preCustomerNo, systemSign, subSystemSign, authSubSystem);
                //恒生活授权后用户信息同步给恒易卡系统
                String remark = "授权流程同步用户信息";
                commonService.insertCustomerExtend(authSystem, authSubSystem, remark, preCustomerNo);
            } else {
                //授权记录为2 无效状态时，更新cust_extend与cust_oauth_channel相应记录
                if (oauthChannelPo.getStatus() == 2) {
                    log.info("【统一授权接口】注销后，再授权登录特殊场景>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>参数：{}", oauthChannelPo);
                    String remark = "注销后，再授权登录";
                    commonService.updateChannelById(oauthChannelPo.getId(), 1, remark);
                    commonService.updateCustExtendByAuth(preCustomerNo, authSystem, authSubSystem, 1);
                }
            }
            String loginCode = UUIDUtils.getUUID();
            //todo 存在问题 cust_oauth_token表 保险 与hsh同事授权hengyika无法区分判断问题，
            CustOauthTokenPo po = commonService.getOauthCode(preCustomerNo, authSubSystem);
            if (po != null) {
                //更新------一般调授权接口是新增，不会走到此步(注销后 授权登录可能走到此步)
                commonService.updateCustOauthToken(preCustomerNo, authSubSystem, loginCode, null, CustomerConstants.UNREGISTER_STATUS, subSystemSign);
            } else {
                //token表新增授权记录
                commonService.insertCustOauthToken(preCustomerNo, authSystem, authSubSystem, loginCode, null, CustomerConstants.UNREGISTER_STATUS, subSystemSign);
            }
            map.put("code", loginCode);
            map.put("requestNo", requestNo);
            return map;
        } catch (CustomerException e) {
            log.error("【统一授权接口】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

    @Override
    public Map<String, Object> checkAuth(BaseRequest<UnifyAuthRo> bRequest) {
        log.info("【统一授权状态查询】开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>入参：{}", bRequest);
        try {
            UnifyAuthRo ro = bRequest.getBody();
            UnifyAuthRo.checkBaseParam(ro);
            //本系统标识
            String systemSign = bRequest.getSystemSign();
            String subSystemSign = bRequest.getSubSystemSign();
            String requestNo = ro.getRequestNo();
            String preCustomerNo = ro.getPreCustomerNo();
            //被授权系统标识
            String authSystem = ro.getAuthSystem();
            String authSubSystem = ro.getAuthSubSystem();
            String systemId = CustomerConstants.YZT;
            Map<String, Object> map = new HashMap<>();
            checkUnifyParam(authSystem, authSubSystem);
//            //todo h5接口验签 UNIFY_CHECK_RULE为code验签,否则不校验
//            Map<String, String> checkRuleDictMap = DictionaryFactory.Dict.UNIFY_CHECK_RULE.getDictMap();
//            String checkRule = checkRuleDictMap.get(mainSystemId);
//            if (StringUtils.isNotBlank(checkRule) && (CustomerConstants.UNIFY_CHECK_ALL.equalsIgnoreCase(checkRule) || CustomerConstants.UNIFY_CHECK_CODE.equalsIgnoreCase(checkRule))) {
//                commonService.verifySignature(mainSystemId, ro.getTimestamp(), code, ro.getVerifyCode());
//            }
            //查询preCustomerNo是否存在
            CustomerExtendPo extendPo = commonService.getExistPreCustomerExtend(preCustomerNo,systemSign,subSystemSign);
            if (extendPo == null) {
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "preCustomerNo用户号不存在!");
            }
            //查询cust_oauth_channel渠道表是否存在授权记录
            CustOauthChannelPo oauthChannelPo = commonService.getOauthChannel(preCustomerNo, subSystemSign, authSubSystem);
            boolean granted = false;
            //status 1-已授权；2-未授权
            Integer status = 2;
            //授权状态必须为有效1，若为2无效表示已注销，需要重新授权登录流程
            if (oauthChannelPo != null && oauthChannelPo.getStatus() == 1) {
                // 更新已授权业务系统code值
                String loginCode = UUIDUtils.getUUID();
                commonService.updateCustOauthToken(preCustomerNo, authSubSystem, loginCode, null, CustomerConstants.UNREGISTER_STATUS, subSystemSign);
                granted = true;
                status = 1;
                map.put("code", loginCode);
            }
            map.put("granted", granted);
            map.put("requestNo", requestNo);
            //记录授权登录流水
            commonService.insertCustOauthLoginFlow(ro.getRequestNo(), subSystemSign, authSubSystem, null, preCustomerNo, status);
            return map;
        } catch (CustomerException e) {
            log.error("【统一授权状态查询】异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(e.getCode(), e.getMsg());
        }
    }

}
